#!/usr/bin/env bash
# Deploy validation workers to Vast.ai
# Usage: ./scripts/deploy_validation.sh <offer_id1> <offer_id2> ...
#
# First search for offers manually:
#   vastai search offers 'gpu_name=RTX_3090 num_gpus=1 reliability>0.95 inet_down>200 rentable=true rented=false disk_space>=30' -o 'dph_total'
# Then pass the offer IDs to this script for instant deployment.

set -euo pipefail

if [ $# -eq 0 ]; then
    echo "Usage: $0 <offer_id1> [offer_id2] [offer_id3] ..."
    echo ""
    echo "Search for offers first:"
    echo "  vastai search offers 'gpu_name=RTX_3090 num_gpus=1 reliability>0.95 inet_down>200 rentable=true rented=false disk_space>=30' -o 'dph_total'"
    exit 1
fi

IMAGE="bharathkumar192/validation-worker:latest"
DISK=30

# R2 credentials
R2_ENDPOINT="https://cb908ed13329eb7b186e06ab51bda190.r2.cloudflarestorage.com"
R2_KEY_ID="c3c9190ae7ff98b10271ea8db6940210"
R2_SECRET="eab9394d02b48a865634105b92c74751ec9a311c56884f7aead5d76476c6b576"

# Database (% in password is literal — Vast passes env vars directly, no shell interpretation)
DB_URL="postgresql://postgres.exlkkfpymkpqlxulurel:Chibhakaku%402001@aws-0-us-west-2.pooler.supabase.com:6543/postgres"

ENV_STR="-e R2_ENDPOINT_URL=${R2_ENDPOINT} -e R2_ACCESS_KEY_ID=${R2_KEY_ID} -e R2_SECRET_ACCESS_KEY=${R2_SECRET} -e DATABASE_URL=${DB_URL}"

# SSH key for access
PUB_KEY="ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIB2rweVLWl+kZNxDhdToX8aq+0TSkWNVBp9XXfLwUnlj ubuntu-vast.ai"

# Onstart: inject SSH key, export env, launch worker with auto-restart loop
ONSTART="mkdir -p /root/.ssh; echo '${PUB_KEY}' >> /root/.ssh/authorized_keys; chmod 700 /root/.ssh; chmod 600 /root/.ssh/authorized_keys; env | grep _ >> /etc/environment; cd /app; while true; do python -m validations.main 2>&1 | tee -a /var/log/portal/validation.log; echo 'Worker exited, restarting in 10s...'; sleep 10; done &"

COUNT=0
TOTAL=$#

for OFFER_ID in "$@"; do
    COUNT=$((COUNT + 1))
    WORKER_ID="val-${OFFER_ID}"
    LABEL="val-${OFFER_ID}"

    FULL_ENV="${ENV_STR} -e WORKER_ID=${WORKER_ID} -e GPU_TYPE=RTX_3090"

    echo "[${COUNT}/${TOTAL}] Creating instance from offer ${OFFER_ID} (worker=${WORKER_ID})..."

    vastai create instance "$OFFER_ID" \
        --image "$IMAGE" \
        --disk "$DISK" \
        --ssh --direct \
        --env "$FULL_ENV" \
        --onstart-cmd "$ONSTART" \
        --label "$LABEL" \
        2>&1

    echo "  -> Done"
done

echo ""
echo "Deployed ${TOTAL} workers. Monitor with:"
echo "  vastai show instances"
echo "  vastai logs <instance_id>"
