#!/bin/sh
set -eu

DATA_DIR=/var/lib/pssp

case "${1:-}" in
  configure)
    if ! getent group pssp >/dev/null 2>&1; then
      groupadd --system pssp
    fi
    if ! getent passwd pssp >/dev/null 2>&1; then
      useradd --system --gid pssp --home-dir "$DATA_DIR" --shell /usr/sbin/nologin pssp
    fi
    install -d -o pssp -g pssp -m 0700 "$DATA_DIR"

    if [ ! -f "$DATA_DIR/pssp.toml" ]; then
      echo "Initializing PSSP broker state in $DATA_DIR."
      runuser -u pssp -- /usr/bin/pssp-broker bootstrap \
        --data-dir "$DATA_DIR" \
        --portal-bind 127.0.0.1:8080
      echo "Save the administrator password printed above; it is shown only once."
    fi

    systemctl daemon-reload
    systemctl enable pssp-broker.service
    if [ -n "${2:-}" ]; then
      systemctl try-restart pssp-broker.service
    else
      systemctl start pssp-broker.service
    fi
    echo "PSSP Broker is running as the pssp system user."
    echo "The administration portal is private: ssh -L 8080:127.0.0.1:8080 ubuntu@SERVER"
    echo "Then open http://127.0.0.1:8080 locally."
    echo "Read the pinned WebService key with: sudo journalctl -u pssp-broker -n 100 --no-pager | grep PSSP_AES_ONLY_PUBLIC_KEY"
    ;;
esac
