#!/bin/bash
# alpha-webmailgate — the ONLY writer of /etc/nginx/.webmail_htpasswd, the
# HTTP Basic Auth gate in front of webmail.<domain> (Roundcube).
# Invoked via sudo by www-data. The password arrives on STDIN (one line),
# never in argv, so it stays out of the process list.
#   set <user>   replace the gate's single login (password on stdin)
#   show         print the current username
# nginx reads auth_basic_user_file per request — no reload needed.
set -u
F=/etc/nginx/.webmail_htpasswd

case "${1:-}" in
  set)
    u="${2:-}"
    [[ "$u" =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$ ]] || { echo "BAD_USER" >&2; exit 2; }
    IFS= read -r pass || true
    [ "${#pass}" -ge 6 ] || { echo "SHORT_PASS" >&2; exit 2; }
    hash=$(printf '%s' "$pass" | openssl passwd -6 -stdin) || { echo "HASH_FAIL" >&2; exit 3; }
    printf '%s:%s\n' "$u" "$hash" > "$F.tmp"
    chown root:www-data "$F.tmp"
    chmod 640 "$F.tmp"
    mv "$F.tmp" "$F"
    echo "ok"
    ;;
  show)
    [ -f "$F" ] && cut -d: -f1 "$F" | head -1 || true
    ;;
  *)
    echo "usage: alpha-webmailgate set <user> (password on stdin) | show" >&2
    exit 1
    ;;
esac
