#!/usr/bin/env bash
# Pasang "otak AI" (Ollama) di VPS Ubuntu/Debian terpisah, diamankan token + HTTPS (Caddy).
# Lonestar tetap di cPanel; hanya inferensi model yang jalan di VPS ini.
# Pakai (sebagai root di VPS):   bash setup-ai-server.sh ai.domainmu.com
# Syarat: DNS A-record ai.domainmu.com sudah mengarah ke IP VPS ini (cek: dig +short ai.domainmu.com)
# Opsi env: AI_AGENT_MODEL=qwen3:8b  AI_AGENT_NUM_CTX=16384
set -e
DOMAIN="$1"
[ "$(id -u)" = 0 ] || { echo "✗ Jalankan sebagai root (sudo -i)"; exit 1; }
[ -n "$DOMAIN" ] || { echo "✗ Pakai: bash setup-ai-server.sh ai.domainmu.com"; exit 1; }
command -v apt-get >/dev/null || { echo "✗ Skrip ini untuk Ubuntu/Debian."; exit 1; }
CTX="${AI_AGENT_NUM_CTX:-16384}"

echo "== Spek VPS =="
MEM=$(awk '/MemTotal/ {print int($2/1024)}' /proc/meminfo); CORES=$(nproc)
GPU="tidak ada"; command -v nvidia-smi >/dev/null && nvidia-smi -L >/dev/null 2>&1 && GPU="$(nvidia-smi -L | head -1)"
echo "RAM: ${MEM} MB | CPU: ${CORES} core | GPU: ${GPU} | Disk bebas: $(df -h / | awk 'NR==2{print $4}')"
if   [ "$MEM" -ge 12000 ]; then MODEL="qwen3:8b"
elif [ "$MEM" -ge 6500  ]; then MODEL="qwen3:4b"
elif [ "$MEM" -ge 3500  ]; then MODEL="qwen3:1.7b"
else echo "✗ RAM ${MEM}MB terlalu kecil (minimal ±4GB)."; exit 1; fi
MODEL="${AI_AGENT_MODEL:-$MODEL}"; echo "Model: $MODEL"

PUBIP=$(curl -fs https://ifconfig.me || true); DNSIP=$(getent hosts "$DOMAIN" | awk '{print $1; exit}')
if [ -n "$PUBIP" ] && [ "$PUBIP" != "$DNSIP" ]; then
  echo "⚠ DNS $DOMAIN → '${DNSIP:-belum ada}', IP VPS = $PUBIP. Sertifikat HTTPS gagal kalau DNS belum benar."
  read -r -p "Lanjut juga? [y/N] " a; [ "$a" = y ] || exit 1
fi

echo "== Pasang Ollama =="
command -v ollama >/dev/null || curl -fsSL https://ollama.com/install.sh | sh
mkdir -p /etc/systemd/system/ollama.service.d
cat > /etc/systemd/system/ollama.service.d/override.conf <<EOS
[Service]
Environment="OLLAMA_HOST=127.0.0.1:11434"
Environment="OLLAMA_CONTEXT_LENGTH=$CTX"
Environment="OLLAMA_KEEP_ALIVE=24h"
Environment="OLLAMA_NUM_PARALLEL=1"
Environment="OLLAMA_MAX_LOADED_MODELS=1"
EOS
systemctl daemon-reload; systemctl enable --now ollama; systemctl restart ollama
for i in $(seq 1 30); do curl -fs http://127.0.0.1:11434/api/version >/dev/null && break; sleep 1; done
curl -fs http://127.0.0.1:11434/api/version >/dev/null || { echo "✗ Ollama tidak start: journalctl -u ollama -n 50"; exit 1; }

echo "== Unduh model & buat varian lonestar-agent =="
ollama pull "$MODEL"
cat > /root/Modelfile.lonestar <<EOM
FROM $MODEL
PARAMETER num_ctx $CTX
PARAMETER num_thread $CORES
PARAMETER temperature 0.2
EOM
ollama create lonestar-agent -f /root/Modelfile.lonestar

echo "== Pasang Caddy (HTTPS otomatis + wajib token) =="
if ! command -v caddy >/dev/null; then
  apt-get update -y; apt-get install -y debian-keyring debian-archive-keyring apt-transport-https curl gpg
  curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | gpg --dearmor --yes -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
  curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' > /etc/apt/sources.list.d/caddy-stable.list
  apt-get update -y; apt-get install -y caddy
fi
TOKEN=$(openssl rand -hex 32)
cat > /etc/caddy/Caddyfile <<EOC
$DOMAIN {
	@unauth {
		not header Authorization "Bearer $TOKEN"
	}
	respond @unauth "unauthorized" 401
	reverse_proxy 127.0.0.1:11434 {
		flush_interval -1
	}
}
EOC
chmod 640 /etc/caddy/Caddyfile
systemctl enable --now caddy; systemctl reload caddy || systemctl restart caddy

if command -v ufw >/dev/null; then ufw allow 22/tcp >/dev/null; ufw allow 80/tcp >/dev/null; ufw allow 443/tcp >/dev/null; ufw --force enable >/dev/null; fi

echo "== Tes =="
sleep 3
echo -n "tanpa token (harus 401): "; curl -s -o /dev/null -w "%{http_code}\n" "https://$DOMAIN/v1/models" || true
echo -n "dengan token (harus 200): "; curl -s -o /dev/null -w "%{http_code}\n" -H "Authorization: Bearer $TOKEN" "https://$DOMAIN/v1/models" || true

cat <<EOF2

✓ Selesai. Tempel 4 baris ini ke .env di cPanel (/home/lonestar/lonestar-backend/.env), ganti yang lama, lalu Restart di Setup Node.js App:

AI_AGENT_PROVIDER=local
AI_AGENT_MODEL=lonestar-agent
AI_AGENT_BASE_URL=https://$DOMAIN/v1
AI_AGENT_API_KEY=$TOKEN

(Token itu buatan sendiri untuk mengunci VPS-mu — bukan API key dari provider AI lain. Simpan, jangan dibagikan.)
EOF2
