#!/bin/bash
# ROA2WEB SSH Tunnel Manager - TESTING
# Direct SSH tunnel to Oracle TEST server (LXC 10.0.20.121 with Oracle in Docker)
# No gateway - connects directly to LXC

SSH_SERVER="10.0.20.121"
SSH_PORT="22"
SSH_USER="root"
SSH_KEY="$HOME/.ssh/id_rsa"  # Use WSL user's SSH key for direct connection
LOCAL_PORT="1521"  # Same port as production tunnel for backend compatibility
REMOTE_HOST="localhost"  # Oracle runs on localhost inside LXC (Docker container)
REMOTE_PORT="1521"
TUNNEL_PID_FILE="/tmp/roa_ssh_tunnel_test.pid"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

print_header() {
    echo -e "${BLUE}================================${NC}"
    echo -e "${BLUE} ROA2WEB TEST SSH Tunnel${NC}"
    echo -e "${BLUE}================================${NC}"
}

check_tunnel() {
    if [ -f "$TUNNEL_PID_FILE" ]; then
        local pid=$(cat "$TUNNEL_PID_FILE")
        if ps -p "$pid" > /dev/null 2>&1; then
            return 0  # Tunnel is running
        else
            rm -f "$TUNNEL_PID_FILE"
            return 1  # PID file exists but process is dead
        fi
    fi
    return 1  # No PID file
}

start_tunnel() {
    print_header

    if check_tunnel; then
        echo -e "${YELLOW}⚠️  TEST SSH tunnel is already running (PID: $(cat $TUNNEL_PID_FILE))${NC}"
        return 0
    fi

    # Check if SSH key exists
    if [ ! -f "$SSH_KEY" ]; then
        echo -e "${RED}❌ Error: SSH key not found at $SSH_KEY${NC}"
        echo -e "${YELLOW}Please ensure you have an SSH key pair in ~/.ssh/${NC}"
        echo -e "${YELLOW}Generate one with: ssh-keygen -t rsa -b 4096${NC}"
        exit 1
    fi

    echo -e "${BLUE}🚀 Starting TEST SSH tunnel (DIRECT connection)...${NC}"
    echo -e "   Local port: ${GREEN}127.0.0.1:${LOCAL_PORT}${NC}"
    echo -e "   SSH Server: ${GREEN}${SSH_USER}@${SSH_SERVER}:${SSH_PORT}${NC}"
    echo -e "   Oracle: ${GREEN}${REMOTE_HOST}:${REMOTE_PORT}${NC} (on LXC)"

    # Start SSH tunnel in background (direct connection to LXC)
    ssh -f -N \
        -o StrictHostKeyChecking=no \
        -o ServerAliveInterval=60 \
        -o ServerAliveCountMax=3 \
        -o ExitOnForwardFailure=yes \
        -i "$SSH_KEY" \
        -L "${LOCAL_PORT}:${REMOTE_HOST}:${REMOTE_PORT}" \
        -p "${SSH_PORT}" \
        "${SSH_USER}@${SSH_SERVER}" 2>&1

    local result=$?

    if [ $result -eq 0 ]; then
        # Get the PID of the SSH process we just started
        sleep 1
        local ssh_pid=$(pgrep -f "ssh.*-L.*${LOCAL_PORT}:${REMOTE_HOST}:${REMOTE_PORT}.*${SSH_USER}@${SSH_SERVER}" | head -1)

        if [ -n "$ssh_pid" ]; then
            echo "$ssh_pid" > "$TUNNEL_PID_FILE"
            echo -e "${GREEN}✅ TEST SSH tunnel started successfully (PID: $ssh_pid)${NC}"
            echo -e "   Direct connection to LXC 10.0.20.121"

            # Verify the tunnel is working by checking if the port is listening
            sleep 2
            if lsof -Pi :${LOCAL_PORT} -sTCP:LISTEN -t >/dev/null 2>&1; then
                echo -e "${GREEN}   🔗 Port ${LOCAL_PORT} is accessible${NC}"
            else
                echo -e "${YELLOW}   ⚠️  Port ${LOCAL_PORT} may not be accessible yet${NC}"
            fi

            return 0
        else
            echo -e "${RED}❌ Failed to get tunnel process ID${NC}"
            echo -e "${YELLOW}   Make sure SSH key is copied to LXC: ssh-copy-id roa2web@10.0.20.121${NC}"
            return 1
        fi
    else
        echo -e "${RED}❌ Failed to start TEST SSH tunnel${NC}"
        echo -e "${YELLOW}   Check: 1) SSH key is on LXC, 2) LXC is accessible (ping 10.0.20.121)${NC}"
        return 1
    fi
}

stop_tunnel() {
    print_header

    if ! check_tunnel; then
        echo -e "${YELLOW}⚠️  TEST SSH tunnel is not running${NC}"
        return 0
    fi

    local pid=$(cat "$TUNNEL_PID_FILE")
    echo -e "${BLUE}🛑 Stopping TEST SSH tunnel (PID: $pid)...${NC}"

    kill "$pid" 2>/dev/null
    local result=$?

    if [ $result -eq 0 ]; then
        rm -f "$TUNNEL_PID_FILE"
        echo -e "${GREEN}✅ TEST SSH tunnel stopped successfully${NC}"
        return 0
    else
        echo -e "${RED}❌ Failed to stop TEST SSH tunnel${NC}"
        return 1
    fi
}

status_tunnel() {
    print_header

    if check_tunnel; then
        local pid=$(cat "$TUNNEL_PID_FILE")
        echo -e "${GREEN}✅ TEST SSH tunnel is running (PID: $pid)${NC}"
        echo -e "   Local port: 127.0.0.1:${LOCAL_PORT}"
        echo -e "   Direct to: ${SSH_USER}@${SSH_SERVER}:${SSH_PORT} -> ${REMOTE_HOST}:${REMOTE_PORT}"

        # Check if port is listening
        if lsof -Pi :${LOCAL_PORT} -sTCP:LISTEN -t >/dev/null 2>&1; then
            echo -e "${GREEN}   🔗 Port ${LOCAL_PORT} is accessible${NC}"
        else
            echo -e "${RED}   ⚠️  Port ${LOCAL_PORT} is not accessible${NC}"
        fi

        return 0
    else
        echo -e "${RED}❌ TEST SSH tunnel is not running${NC}"
        return 1
    fi
}

restart_tunnel() {
    print_header
    echo -e "${BLUE}🔄 Restarting TEST SSH tunnel...${NC}"

    stop_tunnel
    sleep 2
    start_tunnel
}

case "$1" in
    start)
        start_tunnel
        ;;
    stop)
        stop_tunnel
        ;;
    status)
        status_tunnel
        ;;
    restart)
        restart_tunnel
        ;;
    *)
        print_header
        echo "Usage: $0 {start|stop|status|restart}"
        echo ""
        echo "Commands:"
        echo "  start   - Start the TEST SSH tunnel (DIRECT to LXC 10.0.20.121)"
        echo "  stop    - Stop the TEST SSH tunnel"
        echo "  status  - Check TEST SSH tunnel status"
        echo "  restart - Restart the TEST SSH tunnel"
        echo ""
        echo "TEST Tunnel Configuration (Direct Connection):"
        echo "  Local Port:  ${LOCAL_PORT} (localhost:${LOCAL_PORT})"
        echo "  SSH Server:  ${SSH_USER}@${SSH_SERVER}:${SSH_PORT} (direct - no gateway)"
        echo "  Oracle:      ${REMOTE_HOST}:${REMOTE_PORT} (on LXC)"
        echo "  SSH Key:     ${SSH_KEY}"
        echo ""
        echo "Prerequisites:"
        echo "  1. Copy your SSH key to LXC: ssh-copy-id roa2web@10.0.20.121"
        echo "  2. Test direct connection: ssh roa2web@10.0.20.121"
        echo ""
        exit 1
        ;;
esac

exit $?
