#!/usr/bin/env bash
# ObfusGated VPN Kill Switch Emergency Reset (DEB version)
# Run this script if kill switch has blocked your internet connection
#
# This is the "nuclear option" for when you're locked out of internet.
# It will:
# - Remove all kill switch firewall rules
# - Attempt to restore default network routing
# - Clear kill switch persistent settings

echo ""
echo "╔══════════════════════════════════════════════════════════════════════╗"
echo "║           ObfusGated VPN - Kill Switch Emergency Reset               ║"
echo "╚══════════════════════════════════════════════════════════════════════╝"
echo ""
echo "This will completely disable the kill switch and attempt to restore"
echo "your internet connection."
echo ""
echo "USE THIS IF:"
echo "  • You are locked out of the internet"
echo "  • The VPN connection is stuck"
echo "  • Kill switch is blocking connectivity"
echo ""
echo "WHAT IT DOES:"
echo "  • Removes all kill switch firewall rules (iptables)"
echo "  • Attempts to restore default network routing"
echo "  • Clears kill switch persistent settings"
echo "  • Cleans up VPN tunnel interfaces"
echo ""
echo "You can re-enable the kill switch from Settings after reset."
echo ""
read -rp "Continue with reset? [y/N]: " confirm

if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
  echo ""
  echo "Reset cancelled."
  exit 0
fi

echo ""
echo "Starting emergency reset..."
echo ""

DAEMON_SOCK="/run/obfusgated-vpn/daemon.sock"
CONFIG_DIR="$HOME/.config/obfusgated-vpn"
RESULTS=()
SUCCESS=true

# Function to add result
add_result() {
  RESULTS+=("$1")
  echo "  $1"
}

# Step 1: Try to use daemon for reset (preferred - has full routing info)
if [ -S "$DAEMON_SOCK" ]; then
  echo "[1/4] Attempting reset via daemon..."
  
  # Send emergency reset command to daemon
  RESPONSE=$(echo '{"cmd":"killSwitchEmergencyReset","args":[],"id":"reset"}' | \
    timeout 10 nc -U "$DAEMON_SOCK" 2>/dev/null | head -1)
  
  if echo "$RESPONSE" | grep -q '"code":0'; then
    add_result "✓ Daemon reset successful"
    
    # Parse and show results from daemon
    if echo "$RESPONSE" | grep -q '"results"'; then
      echo "  Daemon reported:"
      echo "$RESPONSE" | grep -oP '"results":\[.*?\]' | \
        grep -oP '"[^"]*"' | tr -d '"' | while read -r line; do
          [ -n "$line" ] && echo "    $line"
        done
    fi
  else
    add_result "⚠ Daemon reset returned error, trying direct cleanup"
    SUCCESS=false
  fi
else
  echo "[1/4] Daemon not available, using direct cleanup..."
  echo "  (This may require elevated privileges)"
fi

# Step 2: Direct iptables cleanup (fallback or additional)
echo "[2/4] Cleaning up iptables rules..."

# Find iptables
IPTABLES=""
for path in /sbin/iptables /usr/sbin/iptables /bin/iptables /usr/bin/iptables; do
  if [ -x "$path" ]; then
    IPTABLES="$path"
    break
  fi
done

if [ -n "$IPTABLES" ]; then
  # Try with sudo if available
  SUDO=""
  if [ "$(id -u)" != "0" ] && command -v sudo >/dev/null 2>&1; then
    SUDO="sudo"
    echo "  (Using sudo for iptables commands)"
  fi
  
  # Remove our chain from OUTPUT
  $SUDO $IPTABLES -D OUTPUT -j OBFUSGATED_KS 2>/dev/null && \
    add_result "✓ Removed OBFUSGATED_KS from OUTPUT chain" || true
  
  # Flush our chain
  $SUDO $IPTABLES -F OBFUSGATED_KS 2>/dev/null && \
    add_result "✓ Flushed OBFUSGATED_KS chain" || true
  
  # Delete our chain
  $SUDO $IPTABLES -X OBFUSGATED_KS 2>/dev/null && \
    add_result "✓ Deleted OBFUSGATED_KS chain" || true
  
  # Check if chain still exists
  if $SUDO $IPTABLES -L OBFUSGATED_KS -n 2>/dev/null | grep -q "Chain"; then
    add_result "⚠ Kill switch chain still exists (may need root)"
    SUCCESS=false
  fi
else
  add_result "⚠ iptables not found"
  SUCCESS=false
fi

# Clean up IPv6 rules if ip6tables is available
IP6TABLES=""
for path in /sbin/ip6tables /usr/sbin/ip6tables /bin/ip6tables /usr/bin/ip6tables; do
  if [ -x "$path" ]; then
    IP6TABLES="$path"
    break
  fi
done

if [ -n "$IP6TABLES" ]; then
  $SUDO $IP6TABLES -D OUTPUT -j OBFUSGATED_KS6 2>/dev/null && \
    add_result "✓ Removed OBFUSGATED_KS6 from OUTPUT chain" || true
  $SUDO $IP6TABLES -F OBFUSGATED_KS6 2>/dev/null && \
    add_result "✓ Flushed OBFUSGATED_KS6 chain" || true
  $SUDO $IP6TABLES -X OBFUSGATED_KS6 2>/dev/null && \
    add_result "✓ Deleted OBFUSGATED_KS6 chain" || true
  if $SUDO $IP6TABLES -L OBFUSGATED_KS6 -n 2>/dev/null | grep -q "Chain"; then
    add_result "⚠ IPv6 kill switch chain still exists (may need root)"
    SUCCESS=false
  fi
else
  add_result "⚠ ip6tables not found"
fi

# Step 3: Clean up VPN TUN interfaces
echo "[3/4] Cleaning up VPN interfaces..."

IP_CMD=""
for path in /sbin/ip /usr/sbin/ip /bin/ip /usr/bin/ip; do
  if [ -x "$path" ]; then
    IP_CMD="$path"
    break
  fi
done

if [ -n "$IP_CMD" ]; then
  # Find and list any obfus* interfaces
  OBFUS_IFACES=$($IP_CMD link show 2>/dev/null | grep -oP 'obfus\d+' | sort -u)
  
  if [ -n "$OBFUS_IFACES" ]; then
    for iface in $OBFUS_IFACES; do
      $SUDO $IP_CMD link delete "$iface" 2>/dev/null && \
        add_result "✓ Removed VPN interface $iface" || \
        add_result "⚠ Could not remove $iface (may need root)"
    done
  else
    add_result "✓ No VPN interfaces found"
  fi
  
  # Check if default route exists
  DEFAULT_ROUTE=$($IP_CMD route show default 2>/dev/null | head -1)
  if [ -n "$DEFAULT_ROUTE" ]; then
    add_result "✓ Default route exists: $DEFAULT_ROUTE"
  else
    add_result "⚠ No default route found - internet may not work"
    add_result "  You may need to manually add a route:"
    add_result "    sudo ip route add default via YOUR_GATEWAY dev YOUR_INTERFACE"
    SUCCESS=false
  fi
else
  add_result "⚠ ip command not found"
  SUCCESS=false
fi

# Step 4: Clean up state files
echo "[4/4] Cleaning up state files..."

# Daemon state files (in /run)
for f in "/run/obfusgated-vpn/killswitch_persistent.json" \
         "/run/obfusgated-vpn/killswitch_state.json" \
         "$CONFIG_DIR/killswitch_persistent.json" \
         "$CONFIG_DIR/killswitch_state.json"; do
  if [ -f "$f" ]; then
    rm -f "$f" 2>/dev/null && \
      add_result "✓ Cleared $(basename "$f")" || true
  fi
done

# Summary
echo ""
echo "════════════════════════════════════════════════════════════════════════"
echo ""

if $SUCCESS; then
  echo "✓ Kill switch reset completed successfully!"
  echo ""
  echo "Your internet connection should now be restored."
  echo "You can re-enable kill switch from the app's Settings."
else
  echo "⚠ Kill switch reset completed with warnings."
  echo ""
  echo "Some operations may have failed. If internet is still blocked,"
  echo "try running these commands with sudo:"
  echo ""
  echo "  sudo iptables -F OBFUSGATED_KS"
  echo "  sudo iptables -D OUTPUT -j OBFUSGATED_KS"
  echo "  sudo iptables -X OBFUSGATED_KS"
  echo "  sudo ip6tables -F OBFUSGATED_KS6"
  echo "  sudo ip6tables -D OUTPUT -j OBFUSGATED_KS6"
  echo "  sudo ip6tables -X OBFUSGATED_KS6"
  echo ""
  echo "To restore routing (replace with your actual gateway):"
  echo "  sudo ip route add default via 192.168.1.1 dev eth0"
fi

echo ""
echo "════════════════════════════════════════════════════════════════════════"
echo ""
read -rp "Press Enter to exit..."
