#!/bin/bash

export LOCK_FILE="/var/lib/dpkg/lock-frontend"
export LOCK_FILE2="/var/lib/apt/lists/lock"
export WAIT_INTERVAL=5
export MAX_WAIT=300
export ELAPSED=0

if systemctl is-active --quiet unattended-upgrades; then
    systemctl stop unattended-upgrades
fi

while fuser $LOCK_FILE $LOCK_FILE2 >/dev/null 2>&1; do
    sleep $WAIT_INTERVAL
    ELAPSED=$((ELAPSED + WAIT_INTERVAL))
    if [ $ELAPSED -ge $MAX_WAIT ]; then
        PIDS=$(fuser $LOCK_FILE $LOCK_FILE2 2>/dev/null)
        if [ -n "$PIDS" ]; then
            kill -9 $PIDS
        fi
        dpkg --configure -a
        break
    fi
done

rm -f /var/lib/apt/lists/lock
rm -f /var/cache/apt/archives/lock
rm -f /var/lib/dpkg/lock*
dpkg --configure -a

apt update -y
DEBIAN_FRONTEND=noninteractive apt install -y git python3 python3-venv python3-pip ffmpeg libsndfile1 supervisor net-tools espeak-ng

python3 -m venv /root/tts-venv

/root/tts-venv/bin/pip install --upgrade pip
/root/tts-venv/bin/pip install TTS

echo 'export TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD=1' >> /root/.bashrc
echo 'export COQUI_TOS_AGREED=1' >> /root/.bashrc
echo 'source /root/tts-venv/bin/activate' >> /root/.bashrc
source /root/.bashrc

export TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD=1
export COQUI_TOS_AGREED=1
source /root/tts-venv/bin/activate

# tts --list_models
CONFIG_FILE="/etc/supervisor/conf.d/tts-server.conf"

cat > "$CONFIG_FILE" << 'EOF'
[program:tts-server]
command=/root/tts-venv/bin/tts-server --model_name "tts_models/en/sam/tacotron-DDC" --use_cuda true
directory=/root
autostart=true
autorestart=true
stderr_logfile=/var/log/tts-server.err.log
stdout_logfile=/var/log/tts-server.out.log
user=root
environment=COQUI_TOS_AGREED="1",TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD="1"
EOF

echo "Supervisor config written to $CONFIG_FILE"

supervisorctl reread
supervisorctl update
supervisorctl start tts-server


START_TIME=$(date +%s)
TIMEOUT=$((10 * 60))

while true; do
    NOW=$(date +%s)
    ELAPSED=$((NOW - START_TIME))

    if (( ELAPSED >= TIMEOUT )); then
        echo "$(date '+%F %T') Timeout reached after 10 minutes. Exiting."
        exit 1
    fi

    if curl -s --max-time 5 http://127.0.0.1:5002 >/dev/null; then
        echo "$(date '+%F %T') TTS service is working. Exiting."
        break
    else
        echo "$(date '+%F %T') Service not reachable on 5002. Checking again in 10 seconds."
        sleep 10
    fi
done

exit 0
