#!/bin/sh

# autopkgtest check: test authentication via PostgreSQL - simple
#
# Uses queries assembled by authdaemon itself, configuring only table
# and column names.
#
# Author: Markus Wanner <markus@bluegap.ch>

set -eu

. debian/tests/common.sh

backup_config_files
create_test_users

PASSWORD_DATABASE=$(gen_random_password)

# setup the database
echo "create test database..."
postgres_superuser_exec <<EOSQL
  CREATE ROLE courier
    PASSWORD '${PASSWORD_DATABASE}'
    INHERIT LOGIN;

  CREATE DATABASE test
    ENCODING 'utf-8';

  \connect test

  CREATE TABLE users (
    username TEXT PRIMARY KEY,
    password_hash TEXT NOT NULL,
    uid INT NOT NULL,
    gid INT NOT NULL,
    home TEXT NOT NULL
  );

  INSERT INTO users (username, password_hash, uid, gid, home)
    VALUES ('alice', '${PASSWORD_ALICE}',
            ${ALICE_UID}, ${ALICE_GID}, '/home/alice'),
           ('bob',   '${PASSWORD_BOB}',
            ${BOB_UID},   ${BOB_GID},   '/home/bob'),
           ('carol', '${PASSWORD_CAROL}',
            ${CAROL_UID}, ${CAROL_GID}, '/home/carol');

  GRANT SELECT ON users TO courier;
EOSQL

# configure courier authdaemon
cat > /etc/courier/authpgsqlrc << EOF
PGSQL_CONNECTION  host=localhost user=courier \
                  password='${PASSWORD_DATABASE}';
PGSQL_DATABASE    test
PGSQL_USER_TABLE  users
PGSQL_CRYPT_FIELD password_hash
PGSQL_ID_FIELD    username
PGSQL_UID_FIELD   uid
PGSQL_GID_FIELD   gid
PGSQL_HOME_FIELD  home
EOF

cat > /etc/courier/authdaemonrc << EOF
authmodulelist="authpgsql"
daemons=5
authdaemonvar=/run/courier/authdaemon
EOF

echo "restarting courier-authdaemon"
service courier-authdaemon restart

echo "===== authenumerate ====="
authenumerate_as_courier || /bin/true

echo "===== authtest ====="
authtest_as_courier alice
authtest_as_courier bob
authtest_as_courier carol
