#!/usr/bin/env bash
# Deploy the dedicated DDS backoffice beside the existing VPD instance.
set -Eeuo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
APP_DIR="${DDS_BACKOFFICE_APP_DIR:-/home/opc/apps/dds-backoffice}"
PORT="${DDS_BACKOFFICE_PORT:-8083}"

if [[ -f /home/opc/apps/vpd-backoffice/.env ]]; then
  set -a
  . /home/opc/apps/vpd-backoffice/.env
  set +a
fi

cd "$ROOT"
mvn -DskipTests package
mvn install:install-file \
  -Dfile="$ROOT/target/vpd-permission-backoffice-0.1.0-SNAPSHOT.jar.original" \
  -DpomFile="$ROOT/pom.xml"

cd "$ROOT/dds-backoffice"
mvn -DskipTests package
JAR="$ROOT/dds-backoffice/target/dds-permission-backoffice-0.1.0-SNAPSHOT.jar"
[[ -f "$JAR" ]] || { echo "missing jar: $JAR" >&2; exit 1; }

install -d -o opc -g opc "$APP_DIR"

cat > "$APP_DIR/start.sh" <<'START'
#!/usr/bin/env bash
set -Eeuo pipefail
APP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$APP_DIR"
set -a
if [[ -f /home/opc/apps/vpd-backoffice/.env ]]; then
  . /home/opc/apps/vpd-backoffice/.env
fi
if [[ -f "$APP_DIR/.env" ]]; then
  . "$APP_DIR/.env"
fi
set +a

export DDS_BACKOFFICE_PORT="${DDS_BACKOFFICE_PORT:-8083}"
export DDS_BACKOFFICE_BIND_ADDRESS="${DDS_BACKOFFICE_BIND_ADDRESS:-127.0.0.1}"
export DDS_BACKOFFICE_DB_URL="${DDS_BACKOFFICE_DB_URL:-${BACKOFFICE_DB_URL:-}}"
export DDS_BACKOFFICE_PG_PASSWORD="${DDS_BACKOFFICE_PG_PASSWORD:-${DDSUSER_PG_PASSWORD:-}}"
export DDS_BACKOFFICE_MY_PASSWORD="${DDS_BACKOFFICE_MY_PASSWORD:-${DDSUSER_MY_PASSWORD:-}}"
export DDS_BACKOFFICE_BOTH_PASSWORD="${DDS_BACKOFFICE_BOTH_PASSWORD:-${DDSUSER_BOTH_PASSWORD:-}}"
export DDS_BACKOFFICE_NONE_PASSWORD="${DDS_BACKOFFICE_NONE_PASSWORD:-${DDSUSER_NONE_PASSWORD:-}}"
export DDS_BACKOFFICE_TOKEN_PASSWORD="${DDS_BACKOFFICE_TOKEN_PASSWORD:-${DDSUSER_TOKEN_PASSWORD:-}}"
JAVA_OPTS="${DDS_BACKOFFICE_JAVA_OPTS:--Xms32m -Xmx128m}"

PID_FILE="$APP_DIR/app.pid"
LOG_FILE="$APP_DIR/app.log"
if [[ -f "$PID_FILE" ]] && kill -0 "$(cat "$PID_FILE")" >/dev/null 2>&1; then
  echo "already running pid=$(cat "$PID_FILE")"
  exit 0
fi

setsid nohup java $JAVA_OPTS -jar "$APP_DIR/app.jar" > "$LOG_FILE" 2>&1 < /dev/null &
echo $! > "$PID_FILE"
echo "started pid=$(cat "$PID_FILE") log=$LOG_FILE port=$DDS_BACKOFFICE_PORT"
START

cat > "$APP_DIR/stop.sh" <<'STOP'
#!/usr/bin/env bash
set -Eeuo pipefail
APP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PID_FILE="$APP_DIR/app.pid"
if [[ ! -f "$PID_FILE" ]]; then
  echo "not running: pid file not found"
  exit 0
fi
PID="$(cat "$PID_FILE")"
if kill -0 "$PID" >/dev/null 2>&1; then
  kill "$PID"
  for _ in {1..20}; do
    kill -0 "$PID" >/dev/null 2>&1 || break
    sleep 1
  done
fi
rm -f "$PID_FILE"
echo "stopped"
STOP

cat > "$APP_DIR/status.sh" <<'STATUS'
#!/usr/bin/env bash
set -Eeuo pipefail
APP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PID_FILE="$APP_DIR/app.pid"
if [[ -f "$PID_FILE" ]] && kill -0 "$(cat "$PID_FILE")" >/dev/null 2>&1; then
  echo "running pid=$(cat "$PID_FILE")"
else
  echo "stopped"
fi
STATUS

chmod +x "$APP_DIR/start.sh" "$APP_DIR/stop.sh" "$APP_DIR/status.sh"
if [[ ! -f "$APP_DIR/.env" ]]; then
  cat > "$APP_DIR/.env" <<ENV
# DDS instance overrides. Secrets stay in the existing VPD env file or in this file.
export DDS_BACKOFFICE_PORT="$PORT"
export DDS_BACKOFFICE_BIND_ADDRESS="127.0.0.1"
ENV
  chmod 600 "$APP_DIR/.env"
fi

"$APP_DIR/stop.sh" || true
install -o opc -g opc -m 0644 "$JAR" "$APP_DIR/app.jar"
"$APP_DIR/start.sh"

for _ in {1..30}; do
  if "$APP_DIR/status.sh" | grep -q '^running ' && curl -fsS -o /dev/null "http://127.0.0.1:${PORT}/login"; then
    break
  fi
  sleep 1
done
"$APP_DIR/status.sh"
curl -sS -o /tmp/dds-backoffice-login.html -w 'login=%{http_code}\n' "http://127.0.0.1:${PORT}/login"
for path in / /users /groups /roles /permissions /effective-matrix /dds-protection /vpd-policies /dds-provision /vector-knowledge /dds; do
  curl -sS --connect-timeout 3 --max-time 20 -u "${BACKOFFICE_ADMIN_USER:-}:${BACKOFFICE_ADMIN_PASSWORD:-}" \
    -o "/tmp/dds-backoffice-check-${path#/}.html" \
    -w "${path}=%{http_code}\n" "http://127.0.0.1:${PORT}${path}" || true
done
SMOKE_COOKIE="/tmp/dds-backoffice-smoke.cookies"
SMOKE_PAGE="/tmp/dds-backoffice-smoke-page.html"
SMOKE_RESULT="/tmp/dds-backoffice-smoke-result.html"
if curl -sS --connect-timeout 3 --max-time 20 -c "$SMOKE_COOKIE" \
    -u "${BACKOFFICE_ADMIN_USER:-}:${BACKOFFICE_ADMIN_PASSWORD:-}" \
    -o "$SMOKE_PAGE" "http://127.0.0.1:${PORT}/vector-knowledge"; then
  CSRF_TOKEN="$(sed -n 's/.*name="_csrf" value="\([^"]*\)".*/\1/p' "$SMOKE_PAGE" | head -1)"
  if [[ -n "$CSRF_TOKEN" ]]; then
    for smoke_user in both none; do
      curl -sS --connect-timeout 3 --max-time 30 -b "$SMOKE_COOKIE" -c "$SMOKE_COOKIE" \
        -u "${BACKOFFICE_ADMIN_USER:-}:${BACKOFFICE_ADMIN_PASSWORD:-}" \
        -H "X-CSRF-TOKEN: $CSRF_TOKEN" \
        -H 'HX-Request: true' \
        --data-urlencode "_csrf=$CSRF_TOKEN" \
        --data-urlencode "userKey=$smoke_user" \
        --data-urlencode 'query=Oracle VPD ORDS 권한 태그 검색' \
        --data-urlencode 'limit=10' \
        --data-urlencode 'embeddingMode=DEMO' \
        -o "${SMOKE_RESULT}.${smoke_user}" "http://127.0.0.1:${PORT}/vector-knowledge/search" || true
      echo "vector-search-user=${smoke_user}"
      rg -n "DDS 권한으로 검색했습니다|DATA GRANT를 통과|ORA-00942|데이터베이스 오류" \
        "${SMOKE_RESULT}.${smoke_user}" | head -20 || true
    done
  fi
fi
echo "DDS backoffice deployed at ${APP_DIR} (loopback port ${PORT})"
