#!/usr/bin/env bash
# Download the default Piper voice model if it is not already present.
# Used both at image build time and (as a fallback) at container start.
set -euo pipefail

VOICE="${PIPER_VOICE:-en_GB-alan-medium}"
DEST_DIR="${PIPER_VOICE_DIR:-/opt/piper-voices}"
BASE="https://huggingface.co/rhasspy/piper-voices/resolve/v1.0.0"

# en_GB-alan-medium -> en/en_GB/alan/medium
lang2="${VOICE%%-*}"          # en_GB
lang1="${lang2%%_*}"          # en
rest="${VOICE#*-}"            # alan-medium
name="${rest%%-*}"            # alan
quality="${rest#*-}"          # medium
path="${lang1}/${lang2}/${name}/${quality}"

mkdir -p "$DEST_DIR"
onnx="$DEST_DIR/${VOICE}.onnx"
json="$DEST_DIR/${VOICE}.onnx.json"

if [ -f "$onnx" ] && [ -f "$json" ]; then
  echo "[piper] voice already present: $onnx"
  exit 0
fi

echo "[piper] downloading voice $VOICE ..."
wget -q -O "$onnx" "${BASE}/${path}/${VOICE}.onnx"
wget -q -O "$json" "${BASE}/${path}/${VOICE}.onnx.json"
echo "[piper] saved to $onnx"
