#!/bin/bash
# hx-artex-aws-gpu: ephemeral AWS GPU backend for the ARTEX capable LLM rendezvous, used ONLY when the Mac
# (beauxbatons) is out of its compute window. OFF BY DEFAULT AND REFUSES TO RUN unless the owner has opted in.
#
# Owner standing rule (verbatim, 2026-10-23): "I did not approve that. we have rw-man-0* for builds" - personal
# projects must NOT create EC2 instances in RedWeek's AWS accounts, and the owner is on a tight budget ("never
# propose spending"). A GPU instance costs real money. So this helper launches NOTHING unless BOTH:
#   * /etc/ctg-hx-artex-llm/link.env sets AWS_GPU_FALLBACK=1 and a valid AWS_PROFILE, AND
#   * the sentinel file /etc/ctg-hx-artex-llm/aws-gpu-approved exists (the owner's explicit, auditable opt-in).
# Create the sentinel only on the owner's explicit say-so for a specific run/period.
#
# Safety when it IS enabled:
#   * instance tagged ron-test-artex-gpu-<ts>; InstanceInitiatedShutdownBehavior=terminate
#   * cloud-init installs Ollama, pulls $CAPABLE_MODEL, serves on 127.0.0.1:11434, then `shutdown -h +MAX` so
#     the box self-terminates after AWS_GPU_MAX_MINUTES even if `down` is never called
#   * `down` terminates the instance and `confirm` blocks until the API reports it gone
# Reachability: SSH -L from crystalcave to the instance (no public Ollama bind). The caller tunnels onward to
# HOGSMEADE. This helper writes $STATE_DIR/aws-endpoint (host:port) and $STATE_DIR/aws-ssh-target.
set -u
CONF=${HXLL_CONF:-/etc/ctg-hx-artex-llm/link.env}; [ -r "$CONF" ] && . "$CONF"
: "${AWS_GPU_FALLBACK:=0}" "${AWS_PROFILE:=}" "${AWS_REGION:=us-west-2}" "${AWS_GPU_TYPE:=g6.2xlarge}"
: "${AWS_GPU_AMI:=}" "${AWS_GPU_MAX_MINUTES:=120}" "${CAPABLE_MODEL:=qwen3.5:122b-a10b}"
STATE_DIR=${2:-/run/ctg-hx-artex-llm}; mkdir -p "$STATE_DIR" 2>/dev/null
IDFILE="$STATE_DIR/aws-instance-id"
die(){ echo "[hx-artex-aws-gpu] $*" >&2; exit 1; }

guard() {
  [ "$AWS_GPU_FALLBACK" = 1 ] || die "disabled (AWS_GPU_FALLBACK != 1). Owner rule: no AWS for personal projects / never propose spending."
  [ -f /etc/ctg-hx-artex-llm/aws-gpu-approved ] || die "missing owner opt-in sentinel /etc/ctg-hx-artex-llm/aws-gpu-approved - refusing to spend."
  [ -n "$AWS_PROFILE" ] || die "AWS_PROFILE unset."
  [ -n "$AWS_GPU_AMI" ] || die "AWS_GPU_AMI unset (an AMI that serves/installs Ollama)."
  command -v aws >/dev/null 2>&1 || die "aws CLI not found."
}

case "${1:-}" in
  up)
    guard
    ts=$(date +%Y%m%d-%H%M%S); name="ron-test-artex-gpu-$ts"
    ud=$(mktemp); cat > "$ud" <<CLOUD
#!/bin/bash
set -e
which ollama || curl -fsSL https://ollama.com/install.sh | sh
systemctl enable --now ollama || (nohup ollama serve >/var/log/ollama.log 2>&1 &)
sleep 5; ollama pull ${CAPABLE_MODEL}
shutdown -h +${AWS_GPU_MAX_MINUTES}
CLOUD
    id=$(aws --profile "$AWS_PROFILE" --region "$AWS_REGION" ec2 run-instances \
      --image-id "$AWS_GPU_AMI" --instance-type "$AWS_GPU_TYPE" --count 1 \
      --instance-initiated-shutdown-behavior terminate \
      --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=$name},{Key=purpose,Value=artex-ephemeral-gpu}]" \
      --user-data "file://$ud" --query 'Instances[0].InstanceId' --output text) || die "run-instances failed"
    rm -f "$ud"; echo "$id" > "$IDFILE"
    echo "[hx-artex-aws-gpu] launched $id ($name); self-terminates in ${AWS_GPU_MAX_MINUTES} min"
    aws --profile "$AWS_PROFILE" --region "$AWS_REGION" ec2 wait instance-running --instance-ids "$id" || die "instance never ran"
    ip=$(aws --profile "$AWS_PROFILE" --region "$AWS_REGION" ec2 describe-instances --instance-ids "$id" \
      --query 'Reservations[0].Instances[0].PrivateIpAddress' --output text)
    # the agent's ssh must be able to reach $ip (SSM port-forward or VPN); recorded for the caller's -L
    echo "ubuntu@$ip" > "$STATE_DIR/aws-ssh-target"
    echo "127.0.0.1:11434" > "$STATE_DIR/aws-endpoint"
    echo "[hx-artex-aws-gpu] waiting for ${CAPABLE_MODEL} to be pulled (can take minutes on first boot)"
    ;;
  down)
    [ -s "$IDFILE" ] || { echo "[hx-artex-aws-gpu] no instance recorded"; exit 0; }
    id=$(cat "$IDFILE")
    aws --profile "$AWS_PROFILE" --region "$AWS_REGION" ec2 terminate-instances --instance-ids "$id" >/dev/null 2>&1
    echo "[hx-artex-aws-gpu] terminate requested for $id"
    ;;
  confirm)
    [ -s "$IDFILE" ] || { echo "no instance recorded"; exit 0; }
    id=$(cat "$IDFILE")
    aws --profile "$AWS_PROFILE" --region "$AWS_REGION" ec2 wait instance-terminated --instance-ids "$id" \
      && { echo "[hx-artex-aws-gpu] $id confirmed terminated"; rm -f "$IDFILE"; }
    ;;
  *) echo "usage: hx-artex-aws-gpu up|down|confirm [state_dir]" >&2; exit 2 ;;
esac
