#!/bin/bash
# Configure SSH port 2584 on testnet servers
# Run this ON THE SERVER CONSOLE as devops or root

set -e

echo "=== SSH Port 2584 Configuration ==="
echo ""

# Step 1: Verify current SSH status
echo "Step 1: Checking current SSH status..."
sudo systemctl status ssh.service --no-pager | head -5
sudo ss -tlnp | grep sshd || echo "No SSH listening ports found"
echo ""

# Step 2: Backup current config
echo "Step 2: Backing up sshd_config..."
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.manual.$(date +%Y%m%d-%H%M%S)
echo "[OK] Backup created"
echo ""

# Step 3: Create systemd socket override
echo "Step 3: Creating systemd socket override..."
sudo mkdir -p /etc/systemd/system/ssh.socket.d/
cat << 'EOF' | sudo tee /etc/systemd/system/ssh.socket.d/override.conf
[Socket]
ListenStream=
ListenStream=0.0.0.0:22
ListenStream=[::]:22
ListenStream=0.0.0.0:2584
ListenStream=[::]:2584
EOF
echo "[OK] Socket override created (both ports 22 and 2584)"
echo ""

# Step 4: Update sshd_config to accept both ports
echo "Step 4: Updating sshd_config..."
if ! grep -q "^Port " /etc/ssh/sshd_config; then
    sudo sed -i 's/^#Port 22/Port 22\nPort 2584/' /etc/ssh/sshd_config
else
    if ! grep -q "^Port 2584" /etc/ssh/sshd_config; then
        sudo bash -c 'echo "Port 2584" >> /etc/ssh/sshd_config'
    fi
fi
echo "[OK] sshd_config updated"
echo ""

# Step 5: Reload systemd and restart SSH
echo "Step 5: Reloading systemd and restarting SSH services..."
sudo systemctl daemon-reload
sudo systemctl restart ssh.socket
sleep 2
sudo systemctl restart ssh.service
echo "[OK] Services restarted"
echo ""

# Step 6: Verify listening ports
echo "Step 6: Verifying SSH is listening on both ports..."
sleep 3
sudo ss -tlnp | grep sshd
echo ""

# Step 7: Test localhost connections
echo "Step 7: Testing localhost connections..."
ssh -p 22 -o StrictHostKeyChecking=no -o ConnectTimeout=5 localhost "echo 'Port 22: OK'" 2>&1 || echo "Port 22: FAILED"
ssh -p 2584 -o StrictHostKeyChecking=no -o ConnectTimeout=5 localhost "echo 'Port 2584: OK'" 2>&1 || echo "Port 2584: FAILED"
echo ""

echo "=== Configuration Complete ==="
echo "SSH should now be listening on both port 22 and 2584"
echo "Next: Verify remote access works on port 2584, then disable port 22"
