#!/usr/bin/env bash
# Tunggu sampai REST API studiosoft.id hidup, lalu jalankan pass link internal (nomor 4).
set -u
WS="/home/mantapman/.hermes/profiles/atun/workspace"
LOG="/tmp/ss_watcher_link.log"
AUTH="bambangbot:q26r RePo BVy6 pwU2 F3z7 ouyl"
MAKS=75   # iterasi x 60 detik

echo "[$(date -u '+%F %T UTC')] pengawas mulai — menunggu REST API studiosoft.id" | tee -a "$LOG"
for i in $(seq 1 $MAKS); do
  kode=$(curl -s -4 -o /dev/null -w "%{http_code}" --max-time 25 -u "$AUTH" "https://studiosoft.id/wp-json/wp/v2/posts?per_page=1" || echo 000)
  if [ "$kode" = "200" ]; then
    echo "[$(date -u '+%F %T UTC')] API hidup (percobaan $i) — menjalankan pass link internal" | tee -a "$LOG"
    cd "$WS" && python3 -u ss_link_internal_batch.py --apply 2>&1 | tee -a "$LOG"
    echo "[$(date -u '+%F %T UTC')] selesai" | tee -a "$LOG"
    exit 0
  fi
  echo "[$(date -u '+%F %T UTC')] percobaan $i: API balas $kode — tunggu 60 detik" >> "$LOG"
  sleep 60
done
echo "[$(date -u '+%F %T UTC')] API belum hidup setelah $MAKS menit — dihentikan" | tee -a "$LOG"
exit 1
