#!/usr/bin/env bash
# deploy_server.py kintex 블록 복원 원샷 (소유자 승인 2026-07-24)
# 실행: bash deploy/restore_kintex_block.sh
# 동작: 서버 내부에서 백업 → repo 정본 블록 추출 → 앵커 앞 삽입 → py_compile → 서비스 재시작 → 실패 시 롤백
set -euo pipefail
KEY="$HOME/.ssh/guardia_server"
ssh -i "$KEY" -o IdentitiesOnly=yes -o BatchMode=yes root@101.79.17.164 python3 - <<'PYEOF'
import re, subprocess, shutil, sys, py_compile

TARGET = "/opt/zioinfo/deploy_server.py"
BLOCK_SRC = "/opt/kintex/src/deploy/deploy_server_kintex_block.py"
BACKUP = TARGET + ".bak_kintexfix"
ANCHOR = 'logging.info(f"=== {repo} 배포 완료 ===")'

body = open(TARGET, encoding="utf-8").read()
if 'elif repo == "kintex"' in body:
    print("SKIP: kintex 블록이 이미 존재"); sys.exit(0)

raw = open(BLOCK_SRC, encoding="utf-8").read()
m = re.search(r"'''\n(.*?)'''", raw, re.S)
if not m:
    print("FAIL: 블록 추출 실패"); sys.exit(1)
block = m.group(1)

if ANCHOR not in body:
    print("FAIL: 앵커 미발견"); sys.exit(1)

shutil.copy2(TARGET, BACKUP)
idx = body.index(ANCHOR)
line_start = body.rfind("\n", 0, idx) + 1
indent = body[line_start:idx]
new_body = body[:line_start] + block + indent + ANCHOR + body[idx + len(ANCHOR):]
open(TARGET, "w", encoding="utf-8").write(new_body)

try:
    py_compile.compile(TARGET, doraise=True)
except Exception as e:
    shutil.copy2(BACKUP, TARGET)
    print(f"FAIL: py_compile 실패 → 백업 롤백 완료: {e}"); sys.exit(1)

r = subprocess.run(["systemctl", "restart", "zioinfo-deploy"])
if r.returncode != 0:
    shutil.copy2(BACKUP, TARGET)
    subprocess.run(["systemctl", "restart", "zioinfo-deploy"])
    print("FAIL: 재시작 실패 → 백업 롤백 후 재기동"); sys.exit(1)

act = subprocess.run(["systemctl", "is-active", "zioinfo-deploy"], capture_output=True, text=True)
print(f"OK: kintex 블록 삽입 + py_compile 통과 + zioinfo-deploy {act.stdout.strip()}")
PYEOF
