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

TARGET_HOST="${TARGET_HOST:-player@193.8.215.70}"
TARGET_DOMAIN="${TARGET_DOMAIN:-test2.shineup.me}"
REMOTE_UI_DIR="${REMOTE_UI_DIR:-/home/player/SHiNE/shine-ui}"
REMOTE_CADDYFILE="${REMOTE_CADDYFILE:-/etc/caddy/Caddyfile}"

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

cat >"$TMP_DIR/Caddyfile" <<EOF
{
  auto_https disable_redirects
}

agent.shiningpeople.ru {
  redir / /agent/index.html 308
  redir /agent /agent/index.html 308

  handle_path /agent/* {
    reverse_proxy 127.0.0.1:8765
  }
}

$TARGET_DOMAIN {
  encode zstd gzip

  @ws path /ws /ws/*
  handle @ws {
    reverse_proxy 127.0.0.1:7070
  }

  handle {
    root * $REMOTE_UI_DIR
    try_files {path} /index.html
    file_server
    header -Etag
    header {
      Cache-Control "no-store, no-cache, must-revalidate, max-age=0"
      Pragma "no-cache"
      Expires "0"
    }
  }
}

:80 {
  encode zstd gzip

  @ws path /ws /ws/*
  handle @ws {
    reverse_proxy 127.0.0.1:7070
  }

  handle {
    root * $REMOTE_UI_DIR
    try_files {path} /index.html
    file_server
    header -Etag
    header {
      Cache-Control "no-store, no-cache, must-revalidate, max-age=0"
      Pragma "no-cache"
      Expires "0"
    }
  }
}
EOF

ssh -o BatchMode=yes -o ConnectTimeout=20 "$TARGET_HOST" "echo SSH OK" >/dev/null
ssh "$TARGET_HOST" "sudo -n true"
rsync -az "$TMP_DIR/Caddyfile" "$TARGET_HOST:/tmp/caddy-test2.new"
ssh "$TARGET_HOST" "set -euo pipefail; \
  sudo mv -f /tmp/caddy-test2.new '$REMOTE_CADDYFILE'; \
  sudo chown root:root '$REMOTE_CADDYFILE'; \
  sudo caddy validate --config '$REMOTE_CADDYFILE'; \
  sudo systemctl restart caddy"

