#!/bin/bash
# Root: base services for manual libeufin-bank (like merchant/exchange start_base).
# Then interactive shell as libeufin-bank → run start_bank.sh there.
#
# Container: taler-hacktivism-bank
#
# Usage:
#   /root/start_base_services_for_taler_bank.sh
#   /root/start_base_services_for_taler_bank.sh --no-shell
#   /root/start_base_services_for_taler_bank.sh --no-shell --start-bank
#   /root/start_base_services_for_taler_bank.sh --no-shell --start-bank --restart

set -e
CONF=/etc/libeufin/libeufin-bank.conf
LOG_DIR=/var/log/libeufin-bank
PWD_BIN=/usr/local/bin
BANK_STARTER=start_bank.sh
BANK_USER=libeufin-bank

if [ "$(id -u)" -ne 0 ]; then
  echo "Run as root" >&2
  exit 1
fi

NO_SHELL=0
START_BANK=0
BANK_RESTART=0
for arg in "$@"; do
  case "$arg" in
    --no-shell|-n) NO_SHELL=1 ;;
    --start-bank) START_BANK=1; NO_SHELL=1 ;;
    --restart|-r) BANK_RESTART=1 ;;
    --help|-h)
      cat <<'EOF'
Usage: start_base_services_for_taler_bank.sh [options]

  (default)     Start postgres + dirs, then interactive shell as libeufin-bank
  --no-shell    Start base services only, do not open a shell
  --start-bank  After base services, run /usr/local/bin/start_bank.sh as libeufin-bank
                (implies --no-shell)
  --restart     With --start-bank: pass --restart to start_bank.sh
EOF
      exit 0
      ;;
    *)
      echo "Unknown option: $arg" >&2
      exit 2
      ;;
  esac
done

# --- Debian postgresql defaults (pg_createcluster layout) ---
ensure_postgresql() {
  echo "  Debian perms on /etc/postgresql + data/log/run..."
  if [ -d /etc/postgresql ]; then
    chown -R root:postgres /etc/postgresql
    find /etc/postgresql -type d -exec chmod 755 {} \;
    find /etc/postgresql -type f -name '*.conf' -exec chmod 640 {} \;
  fi
  chown -R postgres:postgres /var/lib/postgresql /var/log/postgresql 2>/dev/null || true
  mkdir -p /var/run/postgresql
  chown postgres:postgres /var/run/postgresql
  chmod 2775 /var/run/postgresql 2>/dev/null || chmod 775 /var/run/postgresql

  # Snakeoil TLS key: postgres fails if it cannot read the key (common in rootless images).
  # Prefer fixing perms; if still broken, force ssl=off for local-only DB.
  if [ -f /etc/ssl/private/ssl-cert-snakeoil.key ]; then
    chown root:ssl-cert /etc/ssl/private/ssl-cert-snakeoil.key 2>/dev/null || true
    chmod 640 /etc/ssl/private/ssl-cert-snakeoil.key 2>/dev/null || true
  fi
  for pgconf in /etc/postgresql/*/main/postgresql.conf; do
    [ -f "$pgconf" ] || continue
    if grep -qE '^\s*ssl\s*=' "$pgconf"; then
      sed -i 's/^\s*ssl\s*=.*/ssl = off/' "$pgconf"
    else
      echo "ssl = off" >>"$pgconf"
    fi
  done

  if pg_isready -q 2>/dev/null; then
    echo "  already accepting connections"
    pg_isready || true
    return 0
  fi

  rm -f /var/run/postgresql/.s.PGSQL.*.lock 2>/dev/null || true
  if ! pgrep -u postgres -x postgres >/dev/null 2>&1; then
    rm -f /var/lib/postgresql/*/main/postmaster.pid 2>/dev/null || true
  fi

  if command -v pg_ctlcluster >/dev/null 2>&1 && command -v pg_lsclusters >/dev/null 2>&1; then
    while read -r ver name _rest; do
      [ -n "$ver" ] || continue
      echo "  pg_ctlcluster $ver $name start"
      pg_ctlcluster "$ver" "$name" start 2>/dev/null || true
    done < <(pg_lsclusters --no-header 2>/dev/null || true)
  fi
  if ! pg_isready -q 2>/dev/null; then
    if [ -x /etc/init.d/postgresql ]; then
      /etc/init.d/postgresql start || true
    else
      service postgresql start || true
    fi
  fi
  sleep 1
  pg_isready || true
}

echo "Create log + data dirs... giving permission to ${BANK_USER}:"
mkdir -p "$LOG_DIR" /var/lib/libeufin-bank
chown "${BANK_USER}:${BANK_USER}" "$LOG_DIR" /var/lib/libeufin-bank
chmod 755 "$LOG_DIR" /var/lib/libeufin-bank

echo "Start base services needed for GOA Exploration Bank."
echo ""

echo "1. postgresql:"
ensure_postgresql
# ensure role + DB (postgres:///libeufin) — Debian createuser/createdb as postgres
su -s /bin/bash postgres -c "psql -tc \"SELECT 1 FROM pg_roles WHERE rolname='libeufin-bank'\" | grep -q 1 || createuser -s libeufin-bank" || true
su -s /bin/bash postgres -c "psql -tc \"SELECT 1 FROM pg_database WHERE datname='libeufin'\" | grep -q 1 || createdb -O libeufin-bank libeufin" || true
pg_isready || true

if [ "$START_BANK" -eq 1 ]; then
  echo ""
  echo "2. start_bank.sh as ${BANK_USER}:"
  if [ ! -x "$PWD_BIN/$BANK_STARTER" ]; then
    echo "missing $PWD_BIN/$BANK_STARTER" >&2
    exit 1
  fi
  if [ "$BANK_RESTART" -eq 1 ]; then
    runuser -u "$BANK_USER" -- "$PWD_BIN/$BANK_STARTER" --restart
  else
    runuser -u "$BANK_USER" -- "$PWD_BIN/$BANK_STARTER"
  fi
  exit $?
fi

if [ "$NO_SHELL" -eq 1 ]; then
  echo "Base services started (--no-shell). Next: runuser -u ${BANK_USER} -- $PWD_BIN/$BANK_STARTER [--restart]"
  exit 0
fi

echo "2. Switching now to user ${BANK_USER}, in $PWD_BIN; find executable $BANK_STARTER there!"
echo ""
cd "$PWD_BIN"
# util-linux: -u and -s are mutually exclusive (same as exchange/merchant)
exec runuser -u "$BANK_USER" -- bash
