#!/bin/bash
# ROA2WEB SSH Tunnel Manager
# Manages SSH tunnel to Oracle server for development

SSH_SERVER="roa.romfast.ro"
SSH_PORT="22122"
SSH_USER="roa2web"  # Replace with Bitvise SSH Server username
SSH_KEY="/tmp/roa_oracle_server"
LOCAL_PORT="1521"
REMOTE_HOST="10.0.20.36"  # Oracle server IP on remote network
REMOTE_PORT="1521"
TUNNEL_PID_FILE="/tmp/roa_ssh_tunnel.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 SSH Tunnel Manager${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}⚠️  SSH tunnel is already running (PID: $(cat $TUNNEL_PID_FILE))${NC}"
        return 0
    fi
    
    # Copy SSH key to /tmp with correct permissions (WSL/NTFS fix)
    echo -e "${BLUE}🔧 Setting up SSH key with correct permissions...${NC}"
    cp "$(dirname "$0")/secrets/roa_oracle_server" "$SSH_KEY" 2>/dev/null || true
    chmod 600 "$SSH_KEY" 2>/dev/null || true
    
    echo -e "${BLUE}🔄 Starting SSH tunnel...${NC}"
    echo -e "   Server: ${SSH_SERVER}:${SSH_PORT}"
    echo -e "   Local:  127.0.0.1:${LOCAL_PORT}"
    echo -e "   Remote: ${REMOTE_HOST}:${REMOTE_PORT}"
    echo
    
    # Test SSH connectivity first
    echo -e "${BLUE}🔍 Testing SSH connectivity...${NC}"
    # Note: roa2web user may not have shell access, so just test authentication
    if ! ssh -o ConnectTimeout=10 -o BatchMode=yes -p "$SSH_PORT" -i "$SSH_KEY" "$SSH_USER@$SSH_SERVER" "echo 'SSH connection successful'" 2>/dev/null; then
        echo -e "${YELLOW}⚠️  Command execution failed, but trying tunnel (user may not have shell access)${NC}"
    else
        echo -e "${GREEN}✅ SSH connectivity OK${NC}"
    fi
    echo
    
    # Start the tunnel
    echo -e "${BLUE}🚀 Creating SSH tunnel...${NC}"
    ssh -f -N -L "${LOCAL_PORT}:${REMOTE_HOST}:${REMOTE_PORT}" \
        -p "$SSH_PORT" \
        -i "$SSH_KEY" \
        -o ServerAliveInterval=60 \
        -o ServerAliveCountMax=3 \
        -o ExitOnForwardFailure=yes \
        "$SSH_USER@$SSH_SERVER"
    
    if [ $? -eq 0 ]; then
        # Find and save the tunnel PID
        local tunnel_pid=$(ps aux | grep "ssh.*${LOCAL_PORT}:${REMOTE_HOST}:${REMOTE_PORT}" | grep -v grep | awk '{print $2}')
        if [ -n "$tunnel_pid" ]; then
            echo "$tunnel_pid" > "$TUNNEL_PID_FILE"
            echo -e "${GREEN}✅ SSH tunnel started successfully (PID: $tunnel_pid)${NC}"
            
            # Test the tunnel
            echo -e "${BLUE}🔍 Testing tunnel connectivity...${NC}"
            if timeout 5 bash -c "cat < /dev/null > /dev/tcp/127.0.0.1/$LOCAL_PORT" 2>/dev/null; then
                echo -e "${GREEN}✅ Tunnel is working! Port $LOCAL_PORT is accessible${NC}"
            else
                echo -e "${YELLOW}⚠️  Tunnel created but port $LOCAL_PORT is not responding${NC}"
                echo -e "${YELLOW}   This might be normal if Oracle listener is not running${NC}"
            fi
        else
            echo -e "${RED}❌ Tunnel process not found${NC}"
            return 1
        fi
    else
        echo -e "${RED}❌ Failed to create SSH tunnel${NC}"
        return 1
    fi
}

stop_tunnel() {
    print_header
    
    if ! check_tunnel; then
        echo -e "${YELLOW}⚠️  No SSH tunnel is running${NC}"
        return 0
    fi
    
    local pid=$(cat "$TUNNEL_PID_FILE")
    echo -e "${BLUE}🛑 Stopping SSH tunnel (PID: $pid)...${NC}"
    
    if kill "$pid" 2>/dev/null; then
        rm -f "$TUNNEL_PID_FILE"
        echo -e "${GREEN}✅ SSH tunnel stopped successfully${NC}"
    else
        echo -e "${RED}❌ Failed to stop tunnel process${NC}"
        # Try to clean up stale PID file
        rm -f "$TUNNEL_PID_FILE"
        return 1
    fi
}

status_tunnel() {
    print_header
    
    if check_tunnel; then
        local pid=$(cat "$TUNNEL_PID_FILE")
        echo -e "${GREEN}✅ SSH tunnel is running (PID: $pid)${NC}"
        echo -e "   Local port: 127.0.0.1:$LOCAL_PORT"
        echo -e "   Remote: $SSH_SERVER:$SSH_PORT -> $REMOTE_HOST:$REMOTE_PORT"
        
        # Test port accessibility
        if timeout 2 bash -c "cat < /dev/null > /dev/tcp/127.0.0.1/$LOCAL_PORT" 2>/dev/null; then
            echo -e "${GREEN}   🔗 Port $LOCAL_PORT is accessible${NC}"
        else
            echo -e "${YELLOW}   ⚠️  Port $LOCAL_PORT is not responding${NC}"
        fi
    else
        echo -e "${RED}❌ SSH tunnel is not running${NC}"
    fi
}

restart_tunnel() {
    stop_tunnel
    sleep 2
    start_tunnel
}

show_help() {
    print_header
    echo
    echo -e "${BLUE}Usage: $0 {start|stop|status|restart|help}${NC}"
    echo
    echo -e "${YELLOW}Commands:${NC}"
    echo -e "  start    - Start SSH tunnel to Oracle server"
    echo -e "  stop     - Stop SSH tunnel"
    echo -e "  status   - Show tunnel status"
    echo -e "  restart  - Restart SSH tunnel"
    echo -e "  help     - Show this help message"
    echo
    echo -e "${YELLOW}Configuration:${NC}"
    echo -e "  SSH Server: $SSH_SERVER:$SSH_PORT"
    echo -e "  SSH User:   $SSH_USER"
    echo -e "  SSH Key:    $SSH_KEY"
    echo -e "  Tunnel:     127.0.0.1:$LOCAL_PORT -> $REMOTE_HOST:$REMOTE_PORT"
    echo
    echo -e "${YELLOW}Setup:${NC}"
    echo -e "  1. Update SSH_USER in this script with your Bitvise username"
    echo -e "  2. Install public key in Bitvise SSH Server (see BITVISE_SSH_SETUP.md)"
    echo -e "  3. Run: $0 start"
    echo
}

# Main script logic
case "$1" in
    start)
        start_tunnel
        ;;
    stop)
        stop_tunnel
        ;;
    status)
        status_tunnel
        ;;
    restart)
        restart_tunnel
        ;;
    help|--help|-h)
        show_help
        ;;
    *)
        echo -e "${RED}❌ Invalid command: $1${NC}"
        echo
        show_help
        exit 1
        ;;
esac