#!/bin/bash
# Root: base services for manual merchant (no systemd).
# Pattern (all three stacks): root base → shell as service user → start_*.sh
#
# Container: taler-hacktivism
# Then as taler-merchant-httpd: /usr/local/bin/start_merchant.sh [--restart]
#
# Usage:
#   /root/start_base_services_for_taler.sh              # interactive shell as service user
#   /root/start_base_services_for_taler.sh --no-shell   # base only (automation)

set -e

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

NO_SHELL=0
for arg in "$@"; do
  case "$arg" in
    --no-shell|-n) NO_SHELL=1 ;;
    --help|-h)
      echo "Usage: $0 [--no-shell]"
      exit 0
      ;;
  esac
done

PWD_BIN="/usr/local/bin"
MERCHANT_STARTER="start_merchant.sh"
LOG_DIR=/var/log/taler-merchant
RUN_DIR=/var/run/taler-merchant/httpd

# --- 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
  # Debian package uses setgid sticky on run dir
  chmod 2775 /var/run/postgresql 2>/dev/null || chmod 775 /var/run/postgresql

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

  # Stale socket lock only when not accepting
  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 "Start certbot renewal (background)..."
if [ -x /root/scripts/certbot_renew.sh ]; then
  /root/scripts/certbot_renew.sh &
elif [ -x ./scripts/certbot_renew.sh ]; then
  ./scripts/certbot_renew.sh &
fi

echo "Create log + runtime dirs... permissions for taler-merchant-httpd / www-data:"
mkdir -p "$LOG_DIR" /var/run/taler-merchant "$RUN_DIR"
chown taler-merchant-httpd: "$LOG_DIR"
chmod 755 "$LOG_DIR"
chown taler-merchant-httpd:www-data /var/run/taler-merchant "$RUN_DIR"
chmod 755 /var/run/taler-merchant "$RUN_DIR"
# merchant app data (package default home)
if [ -d /var/lib/taler-merchant ]; then
  chown -R taler-merchant-httpd:www-data /var/lib/taler-merchant 2>/dev/null || true
fi

echo "Start base services needed for Taler Merchant."
echo ""

if [ -f /root/.taler-secrets-env ]; then
  echo -n "Read secrets needed for SMS delivery:"
  set -a
  # shellcheck disable=SC1091
  source /root/.taler-secrets-env && echo " OK"
  set +a
else
  echo "No /root/.taler-secrets-env (SMS may fail)"
fi

echo "1. postgresql:"
ensure_postgresql

echo "2. nginx:"
if [ -x /etc/init.d/nginx ]; then
  /etc/init.d/nginx start 2>/dev/null || nginx || true
else
  service nginx start 2>/dev/null || nginx || true
fi

if [ "$NO_SHELL" -eq 1 ]; then
  echo "Base services started (--no-shell). Next: runuser -u taler-merchant-httpd -- $PWD_BIN/$MERCHANT_STARTER [--restart]"
  exit 0
fi

echo "3. Switching now to user taler-merchant-httpd, in $PWD_BIN; find executable $MERCHANT_STARTER there!"
echo ""
cd "$PWD_BIN"
# util-linux: -u and -s/--shell are mutually exclusive
exec runuser -u taler-merchant-httpd -- env \
  CLICKSEND_API_KEY="${CLICKSEND_API_KEY:-}" \
  CLICKSEND_USERNAME="${CLICKSEND_USERNAME:-}" \
  TELESIGN_AUTH_TOKEN="${TELESIGN_AUTH_TOKEN:-}" \
  bash
