#!/usr/bin/env bash
# cagecore emergency unlock — saf bash, Python gerektirmez.
# Kalıcı kalmış iptables/nft kafes kurallarını söker.
# İdempotent, her zaman exit 0. <1s sürer.
#
# Kurulum: ~/.local/bin/cage-unlock (symlink veya kopya)
# Çalıştırma: cage-unlock   (sudo parola isteyebilir)
set +e

IPT_CHAINS=("cagecore" "opencode_offline")
NFT_TABLES=("cagecore" "opencode-offline")

sudo_prefix=""
if [ "$(id -u)" != "0" ]; then
  sudo_prefix="sudo"
fi

# nft tabloları
if command -v nft >/dev/null 2>&1; then
  for t in "${NFT_TABLES[@]}"; do
    if $sudo_prefix nft list tables 2>/dev/null | grep -qE "inet ${t}\$"; then
      $sudo_prefix nft delete table inet "$t" 2>/dev/null
    fi
  done
fi

# iptables zincirleri
if command -v iptables >/dev/null 2>&1; then
  for c in "${IPT_CHAINS[@]}"; do
    if $sudo_prefix iptables -L "$c" -n >/dev/null 2>&1; then
      # OUTPUT'tan tüm referansları kaldır
      for _i in 1 2 3 4 5; do
        $sudo_prefix iptables -D OUTPUT -j "$c" 2>/dev/null || break
      done
      $sudo_prefix iptables -F "$c" 2>/dev/null
      $sudo_prefix iptables -X "$c" 2>/dev/null
    fi
  done
fi

# Watchdog PID + temp dir
for wd_pid_file in /tmp/cagecore/watchdog.pid /tmp/contcode/watchdog.pid; do
  if [ -f "$wd_pid_file" ]; then
    pid=$(cat "$wd_pid_file" 2>/dev/null)
    [ -n "$pid" ] && kill "$pid" 2>/dev/null
    rm -f "$wd_pid_file"
  fi
done

exit 0
