#!/usr/bin/env bash
# onx-terminal-rotate-secret — yeni secret üret + ttyd restart (günlük cron).
# Aktif oturum kopar; admin yeniden bağlanır (kabul edilebilir).
set -uo pipefail
cat >/dev/null 2>&1 || true
command -v jq >/dev/null 2>&1 || { printf '{"ok":false,"error":"jq yok"}\n'; exit 2; }
F=/etc/onoxsoft/terminal.secret
mkdir -p /etc/onoxsoft
head -c 48 /dev/urandom | base64 | tr -dc 'a-zA-Z0-9' | head -c 40 > "$F.tmp"
chown root:root "$F.tmp"; chmod 0600 "$F.tmp"; mv -f "$F.tmp" "$F"
systemctl restart onoxsoft-ttyd 2>/dev/null || true
# Apache'nin /admin/terminal/ws'e enjekte ettiği Authorization header'ını yeni secret'la
# senkronla + reload (yoksa tarayıcı bağlantısı 401 yer). Best-effort.
SYNCED=false
if /usr/local/onoxsoft/bin/onx-terminal-proxy-auth-sync 2>/dev/null; then SYNCED=true; fi
sleep 1
ACTIVE="$(systemctl is-active onoxsoft-ttyd 2>/dev/null || echo inactive)"
jq -nc --arg a "$ACTIVE" --argjson s "$SYNCED" '{ok:true,rotated:true,active:$a,apache_synced:$s}'
exit 0
