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

# Azure VM login script
SUBSCRIPTION_ID="fee4ea1f-3e5f-45a6-aaa6-dd6b72f20554"
RESOURCE_GROUP="UMA-OPENCLAW-BOTS"
VM_NAME="usaa-openclaw-linux"
DEFAULT_USER="saravana"
DEFAULT_HOST="168.61.21.159"
SSH_KEY="${HOME}/.ssh/id_rsa"
SSH_PORT=22

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

if ! command -v ssh >/dev/null 2>&1; then
  echo "ERROR: ssh is not installed."
  exit 1
fi

if [[ ! -f "$VM_KEY" ]]; then
  echo "ERROR: SSH key not found at $VM_KEY"
  exit 1
fi

chmod 600 "$VM_KEY"

if [[ -z "$VM_HOST" ]] && command -v az >/dev/null 2>&1; then
  VM_HOST="$(az vm show -d \
    --subscription "$SUBSCRIPTION_ID" \
    -g "$RESOURCE_GROUP" \
    -n "$VM_NAME" \
    --query 'publicIps' \
    -o tsv 2>/dev/null || true)"
fi

if [[ -z "$VM_HOST" ]]; then
  VM_HOST="$DEFAULT_HOST"
fi

echo "Connecting to Azure VM"
echo "  VM   : $VM_NAME"
echo "  Host : $VM_HOST"
echo "  User : $VM_USER"
echo "  Port : $VM_PORT"
echo "  Key  : $VM_KEY"
echo "──────────────────────────────────"

exec 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}@${VM_HOST}"
