#!/bin/bash
# Wombat-Email: the panel's accounts, as root (installed by installer/87-panel.sh).
#   wombat-email-admin password [EMAIL]   set (or reset) a panel password; EMAIL defaults to the owner
#   wombat-email-admin forget-devices     every trusted device must use a mailed code again
#   wombat-email-admin log [N]            the last N entries of the panel's log (default 30)
#   wombat-email-admin texts [off]        sign-in codes by text: your Twilio Verify service and API key (off: forget them)
set -euo pipefail
[ "$(id -u)" = 0 ] || { echo "Run it as root."; exit 1; }
. /etc/wombat-email/settings
sql() { PGTZ="${TIMEZONE:-UTC}" runuser -u postgres -- psql -X -q -At -v ON_ERROR_STOP=1 -d wombat_email "$@"; }   # times in local time

# Asks twice, without showing it, or makes one on an empty answer, and leaves the result in $password.
# PROMPT EMAIL
ask_password() {
    local p2 err
    echo "Press Enter to have a strong password made for you, or type your own."
    echo "Your own needs 16+ characters with a lowercase and an uppercase letter, a number and a symbol;"
    echo "no character 3 times in a row; nothing from the email address."
    while true; do
        read -rsp "$1" password; echo
        if [ -z "$password" ]; then
            password=$(E="$2" php -r 'require "/var/www/wombat-email/panel/lib/password.php"; echo password_generate(getenv("E"));')
            echo
            echo "  $password"
            echo
            echo "Save it in your password manager now. It's only shown here, once."
            read -rsp "Press Enter when it's saved: " p2; echo
            return
        fi
        # The panel's own rule (lib/password.php), the same for every password Wombat-Email sets.
        if ! err=$(P="$password" E="$2" php -r 'require "/var/www/wombat-email/panel/lib/password.php";
                $e = password_error(getenv("P"), getenv("E")); if ($e) { echo $e; exit(1); }'); then
            echo "  $err"; continue
        fi
        read -rsp "Once more: " p2; echo
        [ "$password" = "$p2" ] && return
        echo "  They don't match."
    done
}

case ${1:-} in
    password)
        email=${2:-$ADMIN_EMAIL}; email=${email,,}
        [ "$(sql -c "SELECT 1 FROM admins WHERE email = '${email//\'/}'")" = 1 ] || { echo "No panel account for $email."; exit 1; }
        ask_password "New panel password for $email: " "$email"
        hash=$(P="$password" php -r 'echo password_hash(getenv("P"), PASSWORD_ARGON2ID);')
        unset password
        sql -v email="$email" -v hash="$hash" <<'SQL'
UPDATE admins SET password = :'hash' WHERE email = :'email';
UPDATE sessions SET revoked_at = now(), data = '' WHERE revoked_at IS NULL AND admin_id = (SELECT id FROM admins WHERE email = :'email');
INSERT INTO admin_log (admin_email, action, detail) VALUES (:'email', 'password set', 'with wombat-email-admin, as root; all sessions ended');
SQL
        # The owner's address on this server needs a mailbox, or the panel's sign-in codes have nowhere to go.
        domain_id=$(sql -v d="${email#*@}" <<<"SELECT id FROM domains WHERE name = :'d'")
        if [ "$email" = "${ADMIN_EMAIL,,}" ] && [ -n "$domain_id" ] \
           && [ -z "$(sql -v e="$email" <<<"SELECT 1 FROM mailboxes WHERE email = :'e' UNION SELECT 1 FROM aliases WHERE source = :'e'")" ]; then
            echo
            echo "$email is on this server and has no mailbox yet. The panel mails your sign-in codes there, so it needs one."
            echo "Give it its own password, not the panel's. You'll read it in a mail app, like Thunderbird."
            while true; do
                ask_password "New mailbox password for $email: " "$email"
                P="$password" H="$hash" php -r 'exit(password_verify(getenv("P"), getenv("H")) ? 1 : 0);' && break
                echo "  It must be different from the panel password."
            done
            boxhash="{ARGON2ID}$(P="$password" php -r 'echo password_hash(getenv("P"), PASSWORD_ARGON2ID);')"
            unset password
            sql -v id="$domain_id" -v email="$email" -v hash="$boxhash" <<'SQL'
INSERT INTO mailboxes (domain_id, email, password) VALUES (:id, :'email', :'hash');
INSERT INTO admin_log (admin_email, action, detail) VALUES (:'email', 'mailbox added', 'the owner''s, with wombat-email-admin, as root');
SQL
            [ -x /usr/local/sbin/wombat-email-senders ] && /usr/local/sbin/wombat-email-senders || true   # Rspamd's list of mailboxes
            echo "Mailbox $email made. Set it up in your mail app before signing in: the first sign-in mails a code to it."
        fi
        echo "Done: every session of $email has ended. Sign in at https://$(hostname -f)/panel/"
        ;;
    forget-devices)
        n=$(sql -c "WITH d AS (DELETE FROM trusted_devices RETURNING 1) SELECT count(*) FROM d")
        sql -c "INSERT INTO admin_log (action, detail) VALUES ('trusted devices forgotten', '$n, with wombat-email-admin, as root')"
        echo "$n trusted device(s) forgotten: each needs a mailed code next time."
        ;;
    log)
        n=${2:-30}; [[ "$n" =~ ^[0-9]+$ ]] || { echo "N is a number."; exit 2; }
        sql -c "SELECT to_char(at, 'YYYY-MM-DD HH24:MI') || '  ' || coalesce(admin_email, '-') || '  ' || action || CASE WHEN detail <> '' THEN ': ' || detail ELSE '' END || coalesce('  (' || host(ip) || ')', '') FROM admin_log ORDER BY id DESC LIMIT $n"
        ;;
    texts)
        # Your own Twilio account (twilio.com): a Verify service, and a Restricted API key allowed only Verify's
        # verification Create and verification-check Create. The same as Settings in the panel, for when you can't
        # sign in there. The secret is asked hidden; the panel's own file keeps it (only the panel's user reads it).
        f=/etc/wombat-email/panel-texts.ini
        if [ "${2:-}" = off ]; then
            echo "; Sign-in codes by text: off (Settings, or wombat-email-admin texts)." > "$f"; chown wombat-panel:root "$f"; chmod 600 "$f"
            sql -c "INSERT INTO admin_log (action, detail) VALUES ('codes by text off', 'with wombat-email-admin, as root')"
            echo "Codes by text are off: sign-in codes go by mail."
            exit 0
        fi
        read -rp "Twilio Verify Service SID (starts VA): " va
        read -rp "Twilio API key SID (starts SK): " sk
        read -rsp "Twilio API key secret (not shown as you type or paste): " secret; echo
        [[ "$va" =~ ^VA[0-9a-f]{32}$ ]] || { echo "A Service SID is VA and 32 letters and digits (Twilio: Verify, Services). Nothing saved."; exit 1; }
        [[ "$sk" =~ ^SK[0-9a-f]{32}$ ]] || { echo "An API key SID is SK and 32 letters and digits (Twilio: API keys & tokens). Nothing saved."; exit 1; }
        [[ "$secret" =~ ^[A-Za-z0-9]{20,64}$ ]] || { echo "That secret doesn't look like one (letters and digits). Nothing saved."; exit 1; }
        (umask 077; touch "$f")   # a new file is closed from the start
        printf '; Sign-in codes by text (Settings, or wombat-email-admin texts); only the panel can read this.\ntwilio_service = "%s"\ntwilio_key = "%s"\ntwilio_secret = "%s"\n' "$va" "$sk" "$secret" \
            > "$f"; chown wombat-panel:root "$f"; chmod 600 "$f"
        unset secret
        sql -c "INSERT INTO admin_log (action, detail) VALUES ('codes by text on', 'with wombat-email-admin, as root')"
        echo "Codes by text are on. Each admin confirms their mobile number on Account, or you enter it on Admins."
        echo "Admins without a confirmed number still get their codes by mail."
        ;;
    *)
        sed -n '2,6p' "$0" | sed 's/^# \{0,1\}//'; exit 2 ;;
esac
