#!/usr/bin/env bash
# Run this ON the rented GPU server (Ubuntu). It installs FASHN VTON v1.5 and starts the try-on server.
#
#   1) copy the fashn_server folder to the server (from your PC):  scp -r fashn_server USER@IP:~/
#   2) on the server:   export FASHN_API_KEY="your-secret"
#                       bash fashn_cloud_setup.sh
set -euo pipefail

if [ -z "${FASHN_API_KEY:-}" ]; then
  echo 'Set your secret key first:   export FASHN_API_KEY="your-secret"'
  exit 1
fi
SUDO=""; if [ "$(id -u)" -ne 0 ]; then SUDO="sudo"; fi
BASE="$HOME/fashn"
SERVER_DIR="${SERVER_DIR:-$HOME/fashn_server}"     # the folder you copied with scp
if [ ! -f "$SERVER_DIR/server.py" ]; then
  echo "Cannot find $SERVER_DIR/server.py - copy the fashn_server folder here first (scp -r fashn_server USER@IP:~/)."
  exit 1
fi

echo "== 1/6 GPU check =="
nvidia-smi || { echo "No NVIDIA GPU / driver found on this machine."; exit 1; }

echo "== 2/6 System packages =="
$SUDO apt-get update -y
$SUDO apt-get install -y git python3-venv python3-pip curl

echo "== 3/6 Model code =="
mkdir -p "$BASE"; cd "$BASE"
[ -d fashn-vton-1.5 ] || git clone https://github.com/fashn-AI/fashn-vton-1.5.git
cd fashn-vton-1.5

echo "== 4/6 Python environment (a few minutes) =="
[ -d .venv ] || python3 -m venv .venv
# shellcheck disable=SC1091
source .venv/bin/activate
pip install --upgrade pip
pip install -e .
pip install flask==3.0.3 pillow

echo "== 5/6 Weights (about 2 GB) =="
python scripts/download_weights.py --weights-dir ./weights

echo "== 6/6 Does Python see the GPU? =="
python - <<'PY'
import torch
print("CUDA available:", torch.cuda.is_available())
print("GPU:", torch.cuda.get_device_name(0) if torch.cuda.is_available() else "none")
PY

# Server settings: only the secret key (NO CPU-forcing line: this machine has a real GPU)
printf 'FASHN_API_KEY=%s\n' "$FASHN_API_KEY" > "$SERVER_DIR/.env"
chmod 600 "$SERVER_DIR/.env"

# A small start file you can reuse after a reboot
cat > "$BASE/start_server.sh" <<EOS
#!/usr/bin/env bash
cd "$BASE/fashn-vton-1.5"
source .venv/bin/activate
export FASHN_WEIGHTS_DIR="$BASE/fashn-vton-1.5/weights"
exec python "$SERVER_DIR/server.py"
EOS
chmod +x "$BASE/start_server.sh"

echo "== Starting the try-on server in the background =="
nohup "$BASE/start_server.sh" > "$BASE/server.log" 2>&1 &
sleep 6
echo "Health check:"
curl -s http://127.0.0.1:5001/health || echo "(no answer yet - see: tail -n 30 $BASE/server.log)"
echo
echo "Done. Watch the log with:  tail -f $BASE/server.log"
echo "Restart later with:        nohup $BASE/start_server.sh > $BASE/server.log 2>&1 &"
