#!/usr/bin/env bash
# Shared library: loads .env and exposes SSH helpers.
# Sourced by every script in this directory.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
STACK_DIR="$(dirname "$SCRIPT_DIR")"
ENV_FILE="${STACK_DIR}/.env"

if [ ! -f "$ENV_FILE" ]; then
  echo "❌ $ENV_FILE not found. Copy .env.example to .env and fill it in." >&2
  exit 1
fi

# Load .env without leaking variables to the shell history
set -a
# shellcheck disable=SC1090
source "$ENV_FILE"
set +a

: "${VPS_HOST:?VPS_HOST not set in .env}"
: "${VPS_USER:?VPS_USER not set in .env}"
: "${VPS_PORT:=22}"
: "${VPS_AUTH:=password}"

# ssh wrapper — uses password (sshpass) OR key, transparently
vps_ssh() {
  local cmd="${1:-}"
  if [ "$VPS_AUTH" = "password" ]; then
    if ! command -v sshpass >/dev/null; then
      echo "❌ sshpass not installed. Install with: brew install hudochenkov/sshpass/sshpass" >&2
      exit 1
    fi
    if [ -n "$cmd" ]; then
      SSHPASS="$VPS_PASSWORD" sshpass -e \
        ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 \
        -p "$VPS_PORT" "${VPS_USER}@${VPS_HOST}" "$cmd"
    else
      SSHPASS="$VPS_PASSWORD" sshpass -e \
        ssh -o StrictHostKeyChecking=accept-new \
        -p "$VPS_PORT" "${VPS_USER}@${VPS_HOST}"
    fi
  else
    local key="${VPS_SSH_KEY/#\~/$HOME}"
    if [ -n "$cmd" ]; then
      ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 \
        -p "$VPS_PORT" -i "$key" "${VPS_USER}@${VPS_HOST}" "$cmd"
    else
      ssh -o StrictHostKeyChecking=accept-new \
        -p "$VPS_PORT" -i "$key" "${VPS_USER}@${VPS_HOST}"
    fi
  fi
}

# rsync wrapper
vps_rsync() {
  local src="$1" dst="$2"
  if [ "$VPS_AUTH" = "password" ]; then
    SSHPASS="$VPS_PASSWORD" sshpass -e \
      rsync -avz --progress \
      -e "ssh -o StrictHostKeyChecking=accept-new -p $VPS_PORT" \
      "$src" "${VPS_USER}@${VPS_HOST}:${dst}"
  else
    local key="${VPS_SSH_KEY/#\~/$HOME}"
    rsync -avz --progress \
      -e "ssh -o StrictHostKeyChecking=accept-new -p $VPS_PORT -i $key" \
      "$src" "${VPS_USER}@${VPS_HOST}:${dst}"
  fi
}
