#!/bin/bash
# Setup script for autossh persistent SSH connections
# Usage: ./scripts/setup-autossh.sh [production|git|both]

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
SSH_CONFIG="$HOME/.ssh/config"
SERVICE_TYPE="${1:-both}"

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

# Functions
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if autossh is installed
check_autossh() {
    if ! command -v autossh &> /dev/null; then
        log_error "autossh is not installed!"
        echo ""
        echo "Installation:"
        echo "  Ubuntu/Debian: sudo apt install autossh"
        echo "  macOS:         brew install autossh"
        exit 1
    fi
    log_info "autossh is installed: $(which autossh)"
}

# Check if SSH config exists
check_ssh_config() {
    if [ ! -d "$HOME/.ssh" ]; then
        log_info "Creating ~/.ssh directory"
        mkdir -p "$HOME/.ssh"
        chmod 700 "$HOME/.ssh"
    fi

    if [ ! -f "$SSH_CONFIG" ]; then
        log_info "Creating SSH config file"
        touch "$SSH_CONFIG"
        chmod 600 "$SSH_CONFIG"
    fi
}

# Add SSH config entries
add_ssh_config() {
    log_info "Checking SSH config..."

    # Production server config
    if ! grep -q "Host production" "$SSH_CONFIG" 2>/dev/null; then
        log_info "Adding production server config to SSH config"
        cat >> "$SSH_CONFIG" << 'EOF'

# Production Server - Persistent Connection
Host production
    HostName 94.16.110.151
    User deploy
    IdentityFile ~/.ssh/production
    ServerAliveInterval 60
    ServerAliveCountMax 3
    TCPKeepAlive yes
    Compression yes
    StrictHostKeyChecking accept-new
EOF
    else
        log_info "Production server config already exists in SSH config"
    fi

    # Git server config
    if ! grep -q "Host git.michaelschiemer.de" "$SSH_CONFIG" 2>/dev/null; then
        log_info "Adding git server config to SSH config"
        cat >> "$SSH_CONFIG" << 'EOF'

# Git Server - Persistent Connection
Host git.michaelschiemer.de
    HostName git.michaelschiemer.de
    Port 2222
    User git
    IdentityFile ~/.ssh/git_michaelschiemer
    ServerAliveInterval 60
    ServerAliveCountMax 3
    TCPKeepAlive yes
    Compression yes
    StrictHostKeyChecking no
    UserKnownHostsFile /dev/null
EOF
    else
        log_info "Git server config already exists in SSH config"
    fi
}

# Create systemd service
create_systemd_service() {
    local host=$1
    local port=$2
    local service_name="autossh-${host}"
    local service_dir="$HOME/.config/systemd/user"
    
    log_info "Creating systemd service for ${host}..."

    mkdir -p "$service_dir"

    cat > "${service_dir}/${service_name}.service" << EOF
[Unit]
Description=AutoSSH for ${host}
After=network.target

[Service]
Type=simple
Environment="AUTOSSH_GATETIME=0"
Environment="AUTOSSH_POLL=10"
ExecStart=/usr/bin/autossh -M ${port} -N -o "ServerAliveInterval=60" -o "ServerAliveCountMax=3" ${host}
Restart=always
RestartSec=10

[Install]
WantedBy=default.target
EOF

    log_info "Systemd service created: ${service_dir}/${service_name}.service"
}

# Setup systemd services
setup_systemd_services() {
    if ! systemctl --user --version &> /dev/null; then
        log_warn "systemd user services not available (might be on macOS or non-systemd system)"
        log_info "Skipping systemd service setup. See docs/deployment/AUTOSSH-SETUP.md for manual setup."
        return
    fi

    log_info "Setting up systemd services..."

    case "$SERVICE_TYPE" in
        production)
            create_systemd_service "production" "20000"
            systemctl --user daemon-reload
            log_info "To enable: systemctl --user enable autossh-production.service"
            log_info "To start:   systemctl --user start autossh-production.service"
            ;;
        git)
            create_systemd_service "git.michaelschiemer.de" "20001"
            systemctl --user daemon-reload
            log_info "To enable: systemctl --user enable autossh-git.michaelschiemer.de.service"
            log_info "To start:   systemctl --user start autossh-git.michaelschiemer.de.service"
            ;;
        both)
            create_systemd_service "production" "20000"
            create_systemd_service "git.michaelschiemer.de" "20001"
            systemctl --user daemon-reload
            log_info "To enable:"
            log_info "  systemctl --user enable autossh-production.service"
            log_info "  systemctl --user enable autossh-git.michaelschiemer.de.service"
            log_info "To start:"
            log_info "  systemctl --user start autossh-production.service"
            log_info "  systemctl --user start autossh-git.michaelschiemer.de.service"
            ;;
        *)
            log_error "Invalid service type: $SERVICE_TYPE"
            log_info "Usage: $0 [production|git|both]"
            exit 1
            ;;
    esac
}

# Test SSH connections
test_connections() {
    log_info "Testing SSH connections..."

    case "$SERVICE_TYPE" in
        production)
            if ssh -o ConnectTimeout=5 production "echo 'Connection successful'" 2>/dev/null; then
                log_info "? Production server connection successful"
            else
                log_warn "??  Production server connection failed"
                log_info "Make sure SSH key is set up: ssh-keygen -t ed25519 -f ~/.ssh/production"
            fi
            ;;
        git)
            if ssh -o ConnectTimeout=5 git.michaelschiemer.de "echo 'Connection successful'" 2>/dev/null; then
                log_info "? Git server connection successful"
            else
                log_warn "??  Git server connection failed"
                log_info "Make sure SSH key is set up: ssh-keygen -t ed25519 -f ~/.ssh/git_michaelschiemer"
            fi
            ;;
        both)
            if ssh -o ConnectTimeout=5 production "echo 'Connection successful'" 2>/dev/null; then
                log_info "? Production server connection successful"
            else
                log_warn "??  Production server connection failed"
            fi
            if ssh -o ConnectTimeout=5 git.michaelschiemer.de "echo 'Connection successful'" 2>/dev/null; then
                log_info "? Git server connection successful"
            else
                log_warn "??  Git server connection failed"
            fi
            ;;
    esac
}

# Main execution
main() {
    log_info "Setting up autossh for persistent SSH connections"
    echo ""

    check_autossh
    check_ssh_config
    add_ssh_config
    setup_systemd_services
    test_connections

    echo ""
    log_info "Setup complete!"
    echo ""
    log_info "Next steps:"
    echo "  1. Review SSH config: cat ~/.ssh/config"
    echo "  2. Enable systemd services (see output above)"
    echo "  3. Start services (see output above)"
    echo "  4. Check status: systemctl --user status autossh-*.service"
    echo ""
    log_info "Documentation: docs/deployment/AUTOSSH-SETUP.md"
}

main
