#!/bin/bash
# Backup SSH Access Manager
# Manages emergency SSH access when Tailscale is down

BACKUP_PORT=2222
CURRENT_IP=$(curl -4 -s ifconfig.me 2>/dev/null)

show_status() {
    echo "=== Backup SSH Access Status ==="
    echo
    echo "🔧 SSH Configuration:"
    echo "  - Primary SSH port: 22 (Tailscale + direct IP)"
    echo "  - Backup SSH port: $BACKUP_PORT (restricted IP access)"
    echo
    echo "🌐 Current External IP: $CURRENT_IP"
    echo
    echo "🛡️  Firewall Rules for Port $BACKUP_PORT:"
    ufw status numbered | grep $BACKUP_PORT
    echo
    echo "🔍 SSH Service Status:"
    systemctl is-active ssh && echo "  ✅ SSH service is running"
    echo "  Listening ports:"
    ss -tlnp | grep sshd | grep -E ":22|:$BACKUP_PORT"
    echo
}

add_ip() {
    local ip=$1
    if [[ -z "$ip" ]]; then
        echo "Usage: $0 add-ip <IP_ADDRESS>"
        exit 1
    fi

    echo "Adding IP $ip to backup SSH access..."
    ufw allow from $ip to any port $BACKUP_PORT comment "Emergency SSH backup - $ip"
    echo "✅ Added $ip to backup SSH access"
}

remove_ip() {
    local ip=$1
    if [[ -z "$ip" ]]; then
        echo "Usage: $0 remove-ip <IP_ADDRESS>"
        exit 1
    fi

    echo "Removing IP $ip from backup SSH access..."
    # Find and delete the rule
    rule_num=$(ufw status numbered | grep "$ip.*$BACKUP_PORT" | head -1 | sed 's/\[//g' | sed 's/\].*//g' | tr -d ' ')
    if [[ -n "$rule_num" ]]; then
        echo "y" | ufw delete $rule_num
        echo "✅ Removed $ip from backup SSH access"
    else
        echo "❌ IP $ip not found in firewall rules"
    fi
}

update_current_ip() {
    echo "Updating firewall rule for current IP..."
    local old_ip=$(ufw status numbered | grep "Emergency SSH backup access" | head -1 | awk '{print $4}')

    if [[ "$old_ip" != "$CURRENT_IP" ]]; then
        echo "Current IP changed from $old_ip to $CURRENT_IP"
        if [[ -n "$old_ip" ]]; then
            remove_ip $old_ip
        fi
        add_ip $CURRENT_IP
    else
        echo "✅ Current IP $CURRENT_IP is already authorized"
    fi
}

show_connection_info() {
    echo "=== How to Connect via Backup SSH ==="
    echo
    echo "When Tailscale is down, connect using:"
    echo "  ssh -p $BACKUP_PORT root@YOUR_SERVER_IP"
    echo "  ssh -p $BACKUP_PORT gmod@YOUR_SERVER_IP"
    echo
    echo "Example:"
    echo "  ssh -p $BACKUP_PORT root@$(hostname -I | awk '{print $1}')"
    echo
    echo "⚠️  Requirements:"
    echo "  - Your IP must be authorized (currently: $CURRENT_IP)"
    echo "  - SSH key authentication only (no passwords)"
    echo "  - Port $BACKUP_PORT must be accessible from your location"
    echo
}

case "$1" in
    "status"|"")
        show_status
        ;;
    "add-ip")
        add_ip "$2"
        ;;
    "remove-ip")
        remove_ip "$2"
        ;;
    "update-ip")
        update_current_ip
        ;;
    "connect-info")
        show_connection_info
        ;;
    "help")
        echo "Backup SSH Access Manager"
        echo
        echo "Commands:"
        echo "  status        - Show current backup access status"
        echo "  add-ip <ip>   - Add IP address to backup SSH access"
        echo "  remove-ip <ip> - Remove IP address from backup SSH access"
        echo "  update-ip     - Update firewall rule for current IP"
        echo "  connect-info  - Show connection instructions"
        echo "  help          - Show this help"
        ;;
    *)
        echo "Unknown command: $1"
        echo "Use '$0 help' for available commands"
        exit 1
        ;;
esac
