#!/bin/bash

# Logging configuration
LOG_DIR="/var/log/whisper_webui_setup"
LOG_FILE="$LOG_DIR/install_$(date +%Y%m%d_%H%M%S).log"

# Create log directory
mkdir -p "$LOG_DIR"
chmod 755 "$LOG_DIR"

# Logging function
log() {
    local timestamp=$(date "+%Y-%m-%d %H:%M:%S")
    echo "[$timestamp] $1" | tee -a "$LOG_FILE"
}

# Command execution with error checking
execute() {
    log "Executing: $1"
    eval "$1" >> "$LOG_FILE" 2>&1
    if [ $? -ne 0 ]; then
        log "ERROR: Command failed - $1"
        exit 1
    fi
    log "SUCCESS: Command completed - $1"
}

log "Starting Whisper Webui installation process..."

# Update package lists
execute "apt update -y"

# Install Docker
execute "apt install docker.io docker-compose -y"

# Add NVIDIA container toolkit repository
execute "curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg"
execute "curl -s -L https://nvidia.github.io/libnvidia-container/stable/deb/nvidia-container-toolkit.list | sed 's#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g' | sudo tee /etc/apt/sources.list.d/nvidia-container-toolkit.list"

# Update and install NVIDIA toolkit
execute "apt-get update -y"
execute "apt-get install -y nvidia-container-toolkit"

# Configure Docker daemon
log "Configuring Docker daemon..."
cat <<EOF | sudo tee /etc/docker/daemon.json >> "$LOG_FILE" 2>&1
{
    "exec-opts": [
        "native.cgroupdriver=systemd"
    ],
    "log-driver": "json-file",
    "log-opts": {
        "max-size": "100m"
    },
    "default-runtime": "nvidia",
    "runtimes": {
        "nvidia": {
            "args": [],
            "path": "nvidia-container-runtime"
        }
    },
    "storage-driver": "overlay2"
}
EOF
[ $? -eq 0 ] && log "SUCCESS: Docker daemon configured" || log "ERROR: Docker configuration failed"

# Restart Docker
execute "systemctl restart docker"
log "Waiting for Docker to stabilize..."
sleep 2

log "pull registry.cloudclusters.net/public/whisper-webui:v1.0.7 ..."
docker pull registry.cloudclusters.net/public/whisper-webui:v1.0.7

password=`echo $1|base64 -d|jq .password|sed 's/"//g'`
log "input password is $password"
docker run -d -p 7860:7860   --gpus all --name whisper-webui --entrypoint python  registry.cloudclusters.net/public/whisper-webui:v1.0.7  app.py --server_port 7860 --server_name 0.0.0.0 --username admin --password $password
sleep 5

cd ..
rm -f "*whisper_webui*.sh"
log "Start checking whether port 7860 is listening, wait for up to 10 minutes..."


MAX_WAIT_SECONDS=1200     
CHECK_INTERVAL=5      # check every 5 second 

start_time=$(date +%s)
end_time=$((start_time + MAX_WAIT_SECONDS))


while [ $(date +%s) -lt $end_time ]; do
    if ss -tuln 2>/dev/null | grep -q ':7860\b'; then
        log "7860 port is listening"
        exit 0
    fi

    if ! command -v ss &>/dev/null; then
        if netstat -tuln 2>/dev/null | grep -q ':7860\b'; then
            log "7860 port is listening (netstat)"
            exit 0
        fi
    fi

    remaining_time=$((end_time - $(date +%s)))
    log "Port 7860 is not listening, retrying in ${CHECK_INTERVAL} seconds... (${remaining_time}s remaining)"
    sleep $CHECK_INTERVAL
done

log "Error: Port 7860 did not start listening within 20 minutes!"
exit 1
