#!/usr/bin/env bash
set -Eeuo pipefail
umask 077
BASE=/opt/bookindia-bhaione
SERVICE=bookindia-bhaione
NODE=$BASE/runtime/node/bin/node
export PATH="$BASE/runtime/node/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
[[ $EUID == 0 && -f $BASE/.bhaione-managed ]] || { echo 'Run with sudo on the BhaiOne server.' >&2; exit 1; }
case ${1:-help} in
  status)
    systemctl --no-pager status "$SERVICE" || true
    curl -fsS http://127.0.0.1:4581/api/health
    ;;
  pair)
    KIND=${2:-public}
    [[ $KIND == public || $KIND == local ]] || { echo 'Use bhai-one pair [public|local]' >&2; exit 1; }
    PAIR=/run/$SERVICE/pairing.json
    exec 8>/run/lock/bookindia-bhaione-pair.lock
    flock -w 10 8
    systemctl is-active --quiet "$SERVICE" || { echo 'Start the BhaiOne service first.' >&2; exit 1; }
    OLD=$(sha256sum "$PAIR" 2>/dev/null | cut -d' ' -f1 || true)
    systemctl kill --kill-whom=main --signal=SIGUSR1 "$SERVICE"
    for attempt in {1..40}; do
      NEW=$(sha256sum "$PAIR" 2>/dev/null | cut -d' ' -f1 || true)
      if [[ -n $NEW && $NEW != "$OLD" ]]; then
        "$NODE" -e 'const d=JSON.parse(require("fs").readFileSync(process.argv[1]));console.log(d[process.argv[2]==="local"?"localUrl":"url"])' "$PAIR" "$KIND"
        exit 0
      fi
      sleep 0.1
    done
    echo 'Pairing link was not generated. Check sudo bhai-one status.' >&2; exit 1
    ;;
  grok-login|grok-logout|grok-doctor)
    case $1 in grok-login) CMD=login;; grok-logout) CMD=logout;; *) CMD=inspect;; esac
    ARGS=(); [[ $CMD != login ]] || ARGS+=(--device-auth)
    [[ $CMD != inspect ]] || ARGS+=(--json)
    runuser -u "$SERVICE" -- env HOME="$BASE/data" PATH="$PATH" BHAI_DATA_DIR="$BASE/data" PLAYWRIGHT_BROWSERS_PATH="$BASE/data/cache/ms-playwright" "$NODE" "$BASE/current/scripts/grok.mjs" "$CMD" "${ARGS[@]}"
    ;;
  domain) exec bash "$BASE/current/scripts/server/domain.sh";;
  restart) systemctl restart "$SERVICE";;
  backup)
    exec 9>/run/lock/bookindia-bhaione-install.lock
    flock -n 9 || { echo 'An install or backup is already running.' >&2; exit 1; }
    ACTIVE=0; systemctl is-active --quiet "$SERVICE" && ACTIVE=1
    if (( ACTIVE )); then systemctl stop "$SERVICE"; fi
    finish(){ if (( ACTIVE )); then systemctl start "$SERVICE"; fi; }
    trap finish EXIT
    FILE="$BASE/backups/BookIndia-BhaiOne-$(date -u +%Y%m%dT%H%M%S)-$$.tar.gz"
    tar -C /opt --exclude='bookindia-bhaione/backups' --exclude='bookindia-bhaione/data/cache' --exclude='bookindia-bhaione/data/host.lock' --exclude='bookindia-bhaione/data/grok/bin' --exclude='*/node_modules' --exclude='*/dist/downloads' -czf "$FILE" bookindia-bhaione
    chmod 0600 "$FILE"
    sha256sum "$FILE" > "$FILE.sha256"
    echo "Backup: $FILE"
    echo 'Contains private workspace and account credentials. Transfer only over your SSH connection.'
    ;;
  help|*)
    echo 'BhaiOne: status | pair [public|local] | grok-login | grok-logout | grok-doctor | domain | restart | backup'
    ;;
esac
