#!/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 nginx net-tools

git clone https://github.com/devnen/Chatterbox-TTS-Server.git /opt/Chatterbox-TTS-Server
python3 -m venv /opt/tts-venv
/opt/tts-venv/bin/pip install --upgrade pip
/opt/tts-venv/bin/pip install -r /opt/Chatterbox-TTS-Server/requirements-nvidia.txt
#sed -i 's/^\(\s*host:\s*\).*$/\1127.0.0.1/' /opt/Chatterbox-TTS-Server/config.yaml

sudo tee /etc/supervisor/conf.d/chatterbox.conf > /dev/null << 'EOF'
[program:chatterbox]
directory=/opt/Chatterbox-TTS-Server
command=/bin/bash -c "/opt/tts-venv/bin/python3 /opt/Chatterbox-TTS-Server/server.py"
autostart=true
autorestart=true
stderr_logfile=/var/log/chatterbox.err.log
stdout_logfile=/var/log/chatterbox.out.log
user=root
environment=PYTHONUNBUFFERED="1"
EOF

supervisorctl update
supervisorctl start chatterbox

rm /etc/nginx/sites-enabled/default
CONF_FILE="/etc/nginx/conf.d/chatterbox.conf"
cat > "$CONF_FILE" << 'EOF'
server {
    listen 80 default_server;
    server_name _;

    location / {
        proxy_pass http://127.0.0.1:8000;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
    }
}
EOF
systemctl reload nginx

START_TIME=$(date +%s)
TIMEOUT=$((10 * 60))  # 10 minutes in seconds

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

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

    if curl -s --max-time 5 http://127.0.0.1:8004 >/dev/null \
       && curl -s --max-time 5 http://127.0.0.1 >/dev/null; then
        echo "$(date '+%F %T') Both Chatterbox TTS service and Nginx proxy are working. Exiting."
        break
    else
        echo "$(date '+%F %T') One or both services are not reachable. Checking again in 10 seconds."
        sleep 10
    fi
done


