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

set -euo pipefail

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

echo -e "\e[32m"
cat <<'EOF'
$$\      $$\ $$\                  $$$$$$$$\        $$\ $$\       
$$$\    $$$ |\__|                 \__$$  __|       $$ |$$ |      
$$$$\  $$$$ |$$\  $$$$$$\   $$$$$$\  $$ | $$$$$$\  $$ |$$ |  $$\ 
$$\$$\$$ $$ |$$ |$$  __$$\ $$  __$$\ $$ | \____$$\ $$ |$$ | $$  |
$$ \$$$  $$ |$$ |$$ |  \__|$$ /  $$ |$$ | $$$$$$$ |$$ |$$$$$$  / 
$$ |\$  /$$ |$$ |$$ |      $$ |  $$ |$$ |$$  __$$ |$$ |$$  _$$<  
$$ | \_/ $$ |$$ |$$ |      \$$$$$$  |$$ |\$$$$$$$ |$$ |$$ | \$$\ 
\__|     \__|\__|\__|       \______/ \__| \_______|\__|\__|  \__|

      MiroTalk LK Automated Uninstall Script
        Tested: Ubuntu 22.04 | 24.04 LTS
            (c) 2026 Miroslav Pejic
EOF
echo -e "\e[0m"

#---------------------------------------------
# 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; }
ask()     { local answer=""; read -rp $'⚠️ \e[33m[READ] '"$1"$': \e[0m' answer || true; echo "$answer"; }

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

PROJECT_NAME="mirotalk-lk"
PROJECT_DIR="${PROJECT_DIR:-/root/$PROJECT_NAME}"
NGINX_SITE="/etc/nginx/sites-available/$PROJECT_NAME"
NGINX_SITE_ENABLED="/etc/nginx/sites-enabled/$PROJECT_NAME"
CONTAINERS=(mirotalk-lk mirotalk-lk-livekit mirotalk-lk-redis mirotalk-lk-egress mirotalk-lk-agent mirotalk-lk-whisper mirotalk-lk-whisper-model)
BUILT_IMAGES=(mirotalk-lk:latest mirotalk-lk-agent:latest)

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

#---------------------------------------------
# Confirm
#---------------------------------------------

CONFIRM=$(ask "This removes MiroTalk LK, its containers, .env and Nginx site from this server. Continue? [y/N]")
[[ "${CONFIRM,,}" =~ ^(y|yes)$ ]] || error "Uninstall cancelled."

#---------------------------------------------
# Certificate name (the app domain, from .env)
#---------------------------------------------

DOMAIN="${DOMAIN:-}"
if [[ -z "$DOMAIN" && -f "$PROJECT_DIR/.env" ]]; then
    DOMAIN=$(sed -nE 's|^OG_URL=https?://([^/:]+).*|\1|p' "$PROJECT_DIR/.env" | tail -n1)
fi
if [[ -z "$DOMAIN" ]]; then
    DOMAIN=$(ask "Remove SSL certificates for the app domain (empty to keep them)")
fi

#---------------------------------------------
# Keep or delete recordings
#---------------------------------------------

RECORDINGS_DIR="$PROJECT_DIR/recordings"
if [[ -d "$RECORDINGS_DIR" ]] && [[ -n "$(ls -A "$RECORDINGS_DIR")" ]]; then
    DELETE_RECORDINGS=$(ask "Delete the recordings in $RECORDINGS_DIR too? [y/N]")
    if [[ ! "${DELETE_RECORDINGS,,}" =~ ^(y|yes)$ ]]; then
        BACKUP_DIR="/root/$PROJECT_NAME-recordings-$(date +%Y%m%d-%H%M%S)"
        mv "$RECORDINGS_DIR" "$BACKUP_DIR"
        info "Recordings kept in $BACKUP_DIR"
    fi
fi

#---------------------------------------------
# Stop and remove containers, volumes and built images
#---------------------------------------------

if [[ -f "$PROJECT_DIR/docker-compose.yml" ]] && command -v docker >/dev/null 2>&1; then
    info "Stopping and removing MiroTalk LK containers..."
    (cd "$PROJECT_DIR" && docker compose --profile recording --profile captions --profile whisper \
        down --volumes --rmi local --remove-orphans) || warning "docker compose down failed, removing containers by name."
fi

if command -v docker >/dev/null 2>&1; then
    for name in "${CONTAINERS[@]}"; do
        if docker ps -a --format '{{.Names}}' | grep -qx "$name"; then
            info "Removing container $name..."
            docker rm -f "$name" >/dev/null
        fi
    done
    # Images built on this server (`--rmi local` skips them because docker-compose.yml names them).
    for image in "${BUILT_IMAGES[@]}"; do
        if docker image inspect "$image" >/dev/null 2>&1; then
            info "Removing image $image..."
            docker rmi -f "$image" >/dev/null
        fi
    done
    docker image prune -f >/dev/null
fi

#---------------------------------------------
# Remove the project directory
#---------------------------------------------

if [[ -d "$PROJECT_DIR" ]]; then
    info "Removing $PROJECT_DIR folder..."
    rm -rf "$PROJECT_DIR"
fi

#---------------------------------------------
# Remove Nginx site config
#---------------------------------------------

if [[ -e "$NGINX_SITE_ENABLED" || -L "$NGINX_SITE_ENABLED" ]]; then
    info "Removing Nginx enabled site..."
    rm -f "$NGINX_SITE_ENABLED"
fi

if [[ -f "$NGINX_SITE" ]]; then
    info "Removing Nginx site configuration..."
    rm -f "$NGINX_SITE"
fi

#---------------------------------------------
# Remove SSL certificates for the domain
#---------------------------------------------

if [[ -n "$DOMAIN" ]] && [[ -d "/etc/letsencrypt/live/$DOMAIN" ]] && command -v certbot >/dev/null 2>&1; then
    info "Removing Let's Encrypt SSL certificates for $DOMAIN..."
    certbot delete --cert-name "$DOMAIN" --non-interactive
fi

#---------------------------------------------
# Reload Nginx
#---------------------------------------------

if command -v nginx >/dev/null 2>&1; then
    info "Reloading Nginx..."
    nginx -t && systemctl reload nginx
fi

info "Uninstallation complete! Docker, Nginx and Certbot are still installed."
