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

# ── Hostinger VM login script ──────────────────────────────────────────────
HOST="srv1491630.hstgr.cloud"
DEFAULT_USER="root"
SSH_KEY="${HOME}/.ssh/id_ed25519"   # change to id_rsa if needed
SSH_PORT=22

# ── Allow overrides via environment variables ──────────────────────────────
VM_USER="${VM_USER:-$DEFAULT_USER}"
VM_PORT="${VM_PORT:-$SSH_PORT}"
VM_KEY="${VM_KEY:-$SSH_KEY}"

# ── Safety checks ──────────────────────────────────────────────────────────
if [[ ! -f "$VM_KEY" ]]; then
    echo "ERROR: SSH key not found at $VM_KEY"
    echo "  Generate one with: ssh-keygen -t ed25519 -C 'hostinger-vm'"
    echo "  Then copy it:      ssh-copy-id -i $VM_KEY ${VM_USER}@${HOST}"
    exit 1
fi

# Ensure key has correct permissions (SSH refuses overly-permissive keys)
chmod 600 "$VM_KEY"

# ── Print connection info ──────────────────────────────────────────────────
echo "Connecting to Hostinger VM"
echo "  Host : $HOST"
echo "  User : $VM_USER"
echo "  Port : $VM_PORT"
echo "  Key  : $VM_KEY"
echo "──────────────────────────────────"

# ── SSH with hardened options ──────────────────────────────────────────────
ssh \
  -i "$VM_KEY" \
  -p "$VM_PORT" \
  -o StrictHostKeyChecking=accept-new \
  -o ServerAliveInterval=60 \
  -o ServerAliveCountMax=3 \
  -o PasswordAuthentication=no \
  -o IdentitiesOnly=yes \
  "${VM_USER}@${HOST}"
