#!/usr/bin/env bash
# One-time Piper TTS setup on millenia as a *user* systemd service (no sudo).
# Idempotent — safe to re-run. Run on the box:
#   bash setup-piper.sh
# To survive logout/reboot, also (once, needs root):
#   sudo loginctl enable-linger "$USER"
set -euo pipefail

PIPER_HOME="$HOME/piper"
VENV="$PIPER_HOME/venv"
VOICES="$PIPER_HOME/voices"
VOICE=en_US-amy-medium
UNIT_DIR="$HOME/.config/systemd/user"
export XDG_RUNTIME_DIR="/run/user/$(id -u)"

echo ">> ffmpeg check (petal transcodes Piper WAV -> mp3 with it):"
command -v ffmpeg >/dev/null || { echo "ffmpeg not found on PATH"; exit 1; }

echo ">> venv + piper-tts[http]"
[ -d "$VENV" ] || python3 -m venv "$VENV"
"$VENV/bin/pip" install --upgrade pip >/dev/null
"$VENV/bin/pip" install "piper-tts[http]"

echo ">> download voice $VOICE"
mkdir -p "$VOICES"
"$VENV/bin/python" -m piper.download_voices "$VOICE" --data-dir "$VOICES"

echo ">> install user service"
mkdir -p "$UNIT_DIR"
install -m 0644 "$(dirname "$0")/piper.service" "$UNIT_DIR/piper.service"
systemctl --user daemon-reload
systemctl --user enable --now piper.service

echo ">> wait + status"
sleep 2
systemctl --user --no-pager --full status piper.service | head -n 6 || true

echo ">> smoke test"
curl -sf -X POST localhost:5005/ \
  -H 'Content-Type: application/json' \
  -d "{\"text\":\"hello there\",\"voice\":\"$VOICE\"}" -o /tmp/piper-test.wav \
  && echo "OK: /tmp/piper-test.wav ($(stat -c%s /tmp/piper-test.wav) bytes)" \
  || { echo "smoke test FAILED"; journalctl --user -u piper.service --no-pager | tail -n 20; exit 1; }
