#!/bin/bash
# SPDX-License-Identifier: AGPL-3.0-only

set -euo pipefail

#---------------------------------------------
# MiroTalk LK Update Script (Root)
#---------------------------------------------

#---------------------------------------------
# Logging
#---------------------------------------------

info()    { echo -e "✅ \e[32m[INFO]\e[0m $*"; }
warning() { echo -e "⚠️ \e[33m[WARNING]\e[0m $*"; }
error()   { echo -e "❌ \e[31m[ERROR]\e[0m $*" >&2; exit 1; }

#---------------------------------------------
# Variables
#---------------------------------------------

PROJECT_DIR="${PROJECT_DIR:-/root/mirotalk-lk}"
APP_PORT=3030

if [[ ${EUID} -ne 0 ]]; then
    error "This script should be run as root."
fi

cd "$PROJECT_DIR" || error "Project directory $PROJECT_DIR not found!"

#---------------------------------------------
# Get the latest code
#---------------------------------------------

info "Pulling the latest MiroTalk LK code..."
git pull --ff-only || error "git pull failed. Local changes to tracked files? Check 'git status' in $PROJECT_DIR."

#---------------------------------------------
# Settings added to .env.example since the last update
#---------------------------------------------

NEW_KEYS=$(comm -23 \
    <(grep -oE '^[A-Z0-9_]+=' .env.example | tr -d '=' | sort -u) \
    <(grep -oE '^#?[[:space:]]*[A-Z0-9_]+=' .env | sed -E 's/^#?[[:space:]]*//; s/=$//' | sort -u))

if [[ -n "$NEW_KEYS" ]]; then
    warning "New settings in .env.example (defaults apply; add them to .env to change them):"
    while read -r key; do echo "    $key"; done <<< "$NEW_KEYS"
fi

#---------------------------------------------
# Rebuild and restart (COMPOSE_PROFILES in .env keeps recording/captions running)
#---------------------------------------------

info "Pulling Docker images..."
docker compose pull --ignore-buildable
info "Rebuilding images..."
docker compose build --pull
info "Restarting containers..."
docker compose up -d --remove-orphans
docker image prune -f

info "Waiting for the app to become healthy..."
for _ in $(seq 1 60); do
    curl -fsS "http://127.0.0.1:$APP_PORT/healthz" >/dev/null 2>&1 && break
    sleep 2
done
curl -fsS "http://127.0.0.1:$APP_PORT/healthz" >/dev/null 2>&1 \
    || error "The app did not start. Check the logs: cd $PROJECT_DIR && docker compose logs app"

info "MiroTalk LK updated to $(git log -1 --format='%h (%cs)')"
