#!/usr/bin/env bash
# Deploy neucodec worker on a fresh 4090 machine.
# Usage: curl -sL <url>/deploy.sh | bash
#   or:  bash deploy.sh [--worker-id my-worker-01]
set -euo pipefail

WORKER_ID="${1:-$(hostname)-$(head -c4 /dev/urandom | xxd -p)}"
WORKDIR="/opt/neucodec"

echo "=== Neucodec Worker Deploy ==="
echo "Worker ID: $WORKER_ID"
echo "GPU: $(nvidia-smi --query-gpu=name --format=csv,noheader 2>/dev/null || echo 'not detected')"

# Install system deps
sudo apt-get update -qq && sudo apt-get install -y -qq python3-pip libsndfile1 > /dev/null 2>&1

# Setup workdir
sudo mkdir -p "$WORKDIR"
sudo chown "$(whoami)" "$WORKDIR"
cd "$WORKDIR"

# Copy files (assumes they're in current dir or fetched from somewhere)
if [ ! -f worker.py ]; then
    echo "ERROR: worker.py not found in $WORKDIR"
    echo "Copy worker.py, .env, and requirements.txt to $WORKDIR first."
    exit 1
fi

# Install Python deps
pip3 install --quiet -r requirements.txt 2>&1 | tail -2

# Pre-download model weights
echo "Pre-downloading neucodec model..."
python3 -c "from neucodec import NeuCodec; NeuCodec.from_pretrained('neuphonic/neucodec')" 2>/dev/null

# Load env
set -a
source .env
set +a

# Run worker
echo "Starting worker: $WORKER_ID"
exec python3 worker.py --worker-id "$WORKER_ID"
