#!/usr/bin/env bash
set -euo pipefail

# Alpine SSH Setup Automation
# Configures SSH on Alpine virt ISO via telnet serial console
# Usage: ./alpine-ssh-setup.sh [serial_port]

SERIAL_PORT="${1:-4402}"
TIMEOUT=60

echo "=== Alpine SSH Setup Automation ==="
echo "Connecting to telnet serial console on port ${SERIAL_PORT}..."
echo "This will configure SSH access on Alpine virt ISO"
echo ""

# Wait for Alpine boot (check if telnet port is ready)
echo "Waiting for serial console to be available..."
for i in {1..30}; do
    if timeout 1 bash -c "echo > /dev/tcp/127.0.0.1/${SERIAL_PORT}" 2>/dev/null; then
        echo "Serial console ready!"
        break
    fi
    if [ $i -eq 30 ]; then
        echo "ERROR: Serial console not available after 30s"
        exit 1
    fi
    sleep 1
done

echo ""
echo "Alpine should be booting. Waiting 45s for login prompt..."
sleep 45

echo ""
echo "Sending SSH configuration commands via serial console..."
echo "(This uses a heredoc piped to telnet with command sequence)"
echo ""

# Send commands via telnet
# Sequence:
#   1. Login as root (empty password)
#   2. Wait for prompt
#   3. Configure SSH
#   4. Exit telnet

{
    sleep 2
    echo ""                                          # Login as root (empty password)
    sleep 2
    echo "setup-apkrepos -f"                         # Setup repos for SSH
    sleep 3
    echo "apk add openssh"                           # Install OpenSSH (if not installed)
    sleep 3
    echo "rc-service sshd start"                     # Start SSH service
    sleep 2
    echo "echo 'PermitRootLogin yes' >> /etc/ssh/sshd_config"
    sleep 2
    echo "rc-service sshd restart"                   # Restart with new config
    sleep 2
    echo "echo 'root:ultracloud' | chpasswd"        # Set root password
    sleep 2
    echo "ip addr show"                              # Show network info
    sleep 2
    echo "echo '=== SSH READY ==="                   # Marker
    sleep 1
    printf '\035'                                     # Telnet escape (Ctrl-])
    sleep 1
    echo "quit"                                       # Quit telnet
} | telnet localhost ${SERIAL_PORT}

echo ""
echo "=== SSH Setup Complete ==="
echo "SSH should now be accessible via:"
echo "  ssh -p 2202 root@localhost"
echo "  Password: ultracloud"
echo ""
echo "Test with: ssh -o StrictHostKeyChecking=no -p 2202 root@localhost 'echo SSH_OK'"
echo ""
