#!/usr/bin/env bash
set -euo pipefail

SRC_DIR="shine-UI"
REMOTE_HOST="${REMOTE_HOST:-player@shineup.me}"
REMOTE_UI_DIR="${REMOTE_UI_DIR:-/home/player/SHiNE/shine-ui}"
EXPECTED_CADDY_UI_ROOT="${EXPECTED_CADDY_UI_ROOT:-/home/player/SHiNE/shine-ui}"
ALLOW_CADDY_MISMATCH="${ALLOW_CADDY_MISMATCH:-0}"
EXPECTED_CADDY_SITE="${EXPECTED_CADDY_SITE:-shineup.me}"
BUILD_VERSION="$(date -u +%Y%m%d%H%M%S)"
VERSION_FILE="VERSION.properties"
export BUILD_VERSION
TMP_DIR="$(mktemp -d)"

if [[ ! -f "$VERSION_FILE" ]]; then
  echo "ERROR: version file not found: $VERSION_FILE" >&2
  exit 1
fi

CLIENT_VERSION="$(sed -n "s/^client\\.version[[:space:]]*=[[:space:]]*//p" "$VERSION_FILE" | head -n 1 | tr -d '\r' | xargs)"
if [[ -z "$CLIENT_VERSION" ]]; then
  echo "ERROR: client.version is empty in $VERSION_FILE" >&2
  exit 1
fi
export CLIENT_VERSION

TARGET_URL="https://shineup.me"
REMOTE_DIR="${REMOTE_UI_DIR}"

cleanup() {
  rm -rf "$TMP_DIR"
}
trap cleanup EXIT

if [[ ! -d "$SRC_DIR" ]]; then
  echo "ERROR: source directory not found: $SRC_DIR" >&2
  exit 1
fi

echo "==> Preparing staged UI copy with build version: $BUILD_VERSION"
echo "==> Client version from $VERSION_FILE: $CLIENT_VERSION"
echo "==> Deploy target: $TARGET_URL ($REMOTE_DIR)"
rsync -a "$SRC_DIR"/ "$TMP_DIR"/

INDEX_FILE="$TMP_DIR/index.html"
if [[ ! -f "$INDEX_FILE" ]]; then
  echo "ERROR: index.html not found in staged UI: $INDEX_FILE" >&2
  exit 1
fi

perl -0pi -e 's/window\.__SHINE_BUILD_HASH__\s*=\s*'\''[^'\'']*'\'';/window.__SHINE_BUILD_HASH__ = '\''$ENV{BUILD_VERSION}'\'';/' "$INDEX_FILE"
perl -0pi -e 's/window\.__SHINE_CLIENT_VERSION__\s*=\s*'\''[^'\'']*'\'';/window.__SHINE_CLIENT_VERSION__ = '\''$ENV{CLIENT_VERSION}'\'';/' "$INDEX_FILE"

echo "==> Checking SSH connectivity to $REMOTE_HOST"
ssh -o BatchMode=yes -o ConnectTimeout=10 "$REMOTE_HOST" "echo SSH OK" >/dev/null

echo "==> Validating Caddy UI root"
CADDY_CONFIG_PATH="$(ssh "$REMOTE_HOST" "set -e; \
  exec_line=\$(systemctl show -p ExecStart caddy --value 2>/dev/null || true); \
  cfg=\$(printf '%s' \"\$exec_line\" | sed -n 's/.*--config \\([^ ]*\\).*/\\1/p' | head -n 1); \
  if [ -z \"\$cfg\" ]; then cfg=/etc/caddy/Caddyfile; fi; \
  printf '%s' \"\$cfg\"")"
ROOT_CHECK_OUTPUT="$(ssh "$REMOTE_HOST" "set -euo pipefail; \
  cfg='$CADDY_CONFIG_PATH'; \
  site='$EXPECTED_CADDY_SITE'; \
  sudo awk -v site=\"\$site\" '
    BEGIN { in_site=0; depth=0; root_line=\"\"; root_lineno=0; have_site=0; }
    {
      line=\$0;
      trimmed=line;
      sub(/^[[:space:]]+/, \"\", trimmed);
      sub(/[[:space:]]+$/, \"\", trimmed);

      if (!in_site) {
        if (trimmed ~ \"^\" site \"[[:space:]]*\\\\{\") {
          in_site=1;
          have_site=1;
          depth=1;
          next;
        }
      } else {
        if (trimmed ~ /^root[[:space:]]+\\*[[:space:]]+/ && root_line == \"\") {
          root_line=line;
          root_lineno=NR;
        }
        opens=gsub(/\\{/, \"{\", line);
        closes=gsub(/\\}/, \"}\", line);
        depth += (opens - closes);
        if (depth <= 0) {
          in_site=0;
        }
      }
    }
    END {
      if (!have_site) {
        print \"SITE_NOT_FOUND\";
        exit 0;
      }
      if (root_line == \"\") {
        print \"ROOT_NOT_FOUND\";
        exit 0;
      }
      print root_lineno \":\" root_line;
    }
  ' \"\$cfg\"")"

if [[ "$ROOT_CHECK_OUTPUT" == "SITE_NOT_FOUND" ]]; then
  echo "ERROR: Caddy site block not found: $EXPECTED_CADDY_SITE" >&2
  echo "Caddy config: $CADDY_CONFIG_PATH" >&2
  if [[ "$ALLOW_CADDY_MISMATCH" != "1" ]]; then
    echo "Set ALLOW_CADDY_MISMATCH=1 to bypass this check." >&2
    exit 1
  fi
  echo "WARN: proceeding due to ALLOW_CADDY_MISMATCH=1"
elif [[ "$ROOT_CHECK_OUTPUT" == "ROOT_NOT_FOUND" ]]; then
  echo "ERROR: root directive not found inside site block: $EXPECTED_CADDY_SITE" >&2
  echo "Caddy config: $CADDY_CONFIG_PATH" >&2
  if [[ "$ALLOW_CADDY_MISMATCH" != "1" ]]; then
    echo "Set ALLOW_CADDY_MISMATCH=1 to bypass this check." >&2
    exit 1
  fi
  echo "WARN: proceeding due to ALLOW_CADDY_MISMATCH=1"
elif [[ "$ROOT_CHECK_OUTPUT" != *"$EXPECTED_CADDY_UI_ROOT"* ]]; then
  echo "ERROR: Caddy root mismatch for site $EXPECTED_CADDY_SITE. Found: $ROOT_CHECK_OUTPUT" >&2
  echo "Caddy config: $CADDY_CONFIG_PATH" >&2
  echo "Expected path fragment: $EXPECTED_CADDY_UI_ROOT" >&2
  if [[ "$ALLOW_CADDY_MISMATCH" != "1" ]]; then
    echo "Set ALLOW_CADDY_MISMATCH=1 to bypass this check." >&2
    exit 1
  fi
  echo "WARN: proceeding due to ALLOW_CADDY_MISMATCH=1"
fi

echo "==> Preparing remote directory: $REMOTE_DIR"
ssh "$REMOTE_HOST" "sudo mkdir -p '$REMOTE_DIR'"

echo "==> Syncing staged files to $REMOTE_DIR"
rsync -rlvz --delete --omit-dir-times --no-perms --no-owner --no-group \
  --rsync-path="sudo rsync" \
  "$TMP_DIR"/ "$REMOTE_HOST":"$REMOTE_DIR"/

echo "Всё хорошо: $TARGET_URL"
