#!/usr/bin/env bash
# onx-terminal-install — ttyd (statik binary) + systemd unit + secret kur.
# Idempotent. ttyd 127.0.0.1:7681'de, root /bin/bash --login, -c onox:<secret>.
# Secret runtime'da okunur (ExecStart bash -c) → rotate restart edince yeni secret aktif.
set -uo pipefail
INPUT=$(cat 2>/dev/null || echo '{}')

TTYD_BIN=/usr/local/onoxsoft/bin/ttyd
SECRET_FILE=/etc/onoxsoft/terminal.secret
UNIT=/etc/systemd/system/onoxsoft-ttyd.service
TTYD_VER="1.7.7"
ARCH="$(uname -m)"   # x86_64 / aarch64
URL="https://github.com/tsl0922/ttyd/releases/download/${TTYD_VER}/ttyd.${ARCH}"
ACTIONS=()

command -v jq >/dev/null 2>&1 || { printf '{"ok":false,"error":"jq yok"}\n'; exit 2; }

# 1) binary
if [[ ! -x "$TTYD_BIN" ]]; then
  if ! curl -fsSL "$URL" -o "$TTYD_BIN.tmp"; then
    printf '{"ok":false,"error":"ttyd indirilemedi: %s"}\n' "$URL"; exit 3
  fi
  chmod 0755 "$TTYD_BIN.tmp"; mv -f "$TTYD_BIN.tmp" "$TTYD_BIN"
  ACTIONS+=("ttyd ${TTYD_VER} kuruldu")
fi

# 2) secret (yoksa)
if [[ ! -s "$SECRET_FILE" ]]; then
  mkdir -p /etc/onoxsoft
  head -c 48 /dev/urandom | base64 | tr -dc 'a-zA-Z0-9' | head -c 40 > "$SECRET_FILE"
  chown root:root "$SECRET_FILE"; chmod 0600 "$SECRET_FILE"
  ACTIONS+=("secret uretildi")
fi

# 3) systemd unit
cat > "$UNIT" <<'UNITEOF'
[Unit]
Description=OnoxSoft ttyd (admin terminal)
After=network.target

[Service]
Type=simple
ExecStart=/bin/bash -c '/usr/local/onoxsoft/bin/ttyd -i 127.0.0.1 -p 7681 -c "onox:$(cat /etc/onoxsoft/terminal.secret)" -m 2 -t fontSize=14 -t disableLeaveAlert=true --writable /bin/bash --login'
Restart=on-failure
RestartSec=2
KillMode=mixed

[Install]
WantedBy=multi-user.target
UNITEOF
ACTIONS+=("systemd unit yazildi")

systemctl daemon-reload
systemctl enable onoxsoft-ttyd >/dev/null 2>&1 || true
systemctl restart onoxsoft-ttyd
sleep 1
ACTIVE="$(systemctl is-active onoxsoft-ttyd 2>/dev/null || echo inactive)"

# 4) Apache WS-proxy Authorization header include'unu secret'tan üret + (httpd ise) reload.
# ttyd basic-auth ister; tarayıcı WS header ekleyemez → Apache enjekte eder (asıl kapı AuthToken).
if /usr/local/onoxsoft/bin/onx-terminal-proxy-auth-sync 2>/dev/null; then
  ACTIONS+=("apache proxy-auth include senkronlandi")
fi

if [[ ${#ACTIONS[@]} -eq 0 ]]; then ACT_JSON='[]'; else ACT_JSON=$(printf '%s\n' "${ACTIONS[@]}" | jq -R . | jq -sc .); fi
jq -nc --arg active "$ACTIVE" --arg ver "$TTYD_VER" \
  --argjson ok "$([[ "$ACTIVE" == active ]] && echo true || echo false)" --argjson acts "$ACT_JSON" \
  '{ok:$ok,active:$active,ttyd_version:$ver,actions:$acts}'
exit 0
