#!/bin/bash
# entrypoint: download int8 Parakeet weights on first run if the target dir is
# empty, then start the FastAPI app. Idempotent — subsequent starts skip the
# download when the files already exist.

set -euo pipefail

MODEL_DIR=${MODEL_DIR:-/models}
MODEL_URL=${MODEL_URL:-https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-nemo-parakeet-tdt-0.6b-v2-int8.tar.bz2}

required=(encoder.int8.onnx decoder.int8.onnx joiner.int8.onnx tokens.txt)
missing=0
for f in "${required[@]}"; do
    [[ -f "$MODEL_DIR/$f" ]] || missing=1
done

if [[ "$missing" -eq 1 ]]; then
    echo "[entrypoint] model files not present in $MODEL_DIR, downloading from $MODEL_URL"
    mkdir -p "$MODEL_DIR"
    tmp=$(mktemp -d)
    wget -q --show-progress -O "$tmp/model.tar.bz2" "$MODEL_URL"
    tar -xjf "$tmp/model.tar.bz2" -C "$tmp"
    # Upstream tarballs extract to a single top-level dir; move its contents up.
    extracted_root=$(find "$tmp" -mindepth 1 -maxdepth 1 -type d | head -n1)
    shopt -s dotglob
    mv "$extracted_root"/* "$MODEL_DIR"/
    rm -rf "$tmp"
    echo "[entrypoint] model extracted:"
    ls -la "$MODEL_DIR"
fi

exec uvicorn app:app --host 0.0.0.0 --port 8000
