#!/bin/bash
# SPDX-License-Identifier: AGPL-3.0-only
# shellcheck disable=SC1091 # /etc/os-release only exists on the server

set -euo pipefail

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

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

       MiroTalk LK Automated Install 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 (each one can be overridden from the environment)
#---------------------------------------------

PROJECT_NAME="mirotalk-lk"
PROJECT_DIR="${PROJECT_DIR:-/root/$PROJECT_NAME}"
REPO_URL="${REPO_URL:-https://github.com/miroslavpejic85/mirotalk-lk.git}"
REPO_BRANCH="${REPO_BRANCH:-}"             # Empty: the repository's default branch
APP_PORT=3030
LIVEKIT_PORT=7880
MIN_COMPOSE_VERSION="2.24.4"               # Needed for `!override` in docker-compose.override.yml
NGINX_SITE="/etc/nginx/sites-available/$PROJECT_NAME"
NGINX_SITE_ENABLED="/etc/nginx/sites-enabled/$PROJECT_NAME"
ACME_WEBROOT="/var/www/letsencrypt"

DOMAIN="${DOMAIN:-}"                       # App, e.g. meet.example.com
LIVEKIT_DOMAIN="${LIVEKIT_DOMAIN:-}"       # LiveKit signalling (wss), e.g. livekit.example.com
LETSENCRYPT_EMAIL="${LETSENCRYPT_EMAIL:-}" # Default: admin@$DOMAIN
HOST_SIGN_IN="${HOST_SIGN_IN:-}"           # y/n: only signed-in hosts can start meetings
SKIP_DNS_CHECK="${SKIP_DNS_CHECK:-false}"  # true when the domains are behind a proxy/CDN

#---------------------------------------------
# Check root
#---------------------------------------------

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

#---------------------------------------------
# Check OS
#---------------------------------------------

OS=$(. /etc/os-release && echo "${ID:-}")
VERSION=$(. /etc/os-release && echo "${VERSION_ID:-}")

if [[ "$OS" != "ubuntu" ]] || [[ "$VERSION" != "22.04" && "$VERSION" != "24.04" ]]; then
    error "This script only supports Ubuntu 22.04 or 24.04 LTS (found: ${OS:-unknown} ${VERSION:-})."
fi

#---------------------------------------------
# Check CPU, RAM, Disk
#---------------------------------------------

CPU=$(nproc)
RAM=$(free -m | awk '/Mem:/ {print $2}')
DISK=$(df --output=avail -k / | tail -1 | tr -d ' ')
ARCH=$(uname -m)

if [[ $CPU -lt 2 || $RAM -lt 1900 || $DISK -lt 20000000 || ( "$ARCH" != "x86_64" && "$ARCH" != "aarch64" ) ]]; then
    error "Server does not meet requirements:
        - CPU cores >= 2 (found $CPU)
        - RAM >= 2GB (found ${RAM}MB)
        - Free disk >= 20GB (found ${DISK}KB)
        - Architecture x86_64 or aarch64 (found $ARCH)"
fi

info "System requirements OK: CPU=$CPU, RAM=${RAM}MB, Disk=${DISK}KB, Arch=$ARCH"

#---------------------------------------------
# Check for a previous installation
#---------------------------------------------

if [[ -e "$PROJECT_DIR" ]]; then
    error "$PROJECT_DIR already exists. Run lk-update.sh to update, or lk-uninstall.sh first to reinstall."
fi

if command -v apache2 >/dev/null 2>&1 && systemctl is-active --quiet apache2; then
    error "Apache is running and would block ports 80/443 for Nginx. Stop or remove it, then run this script again."
fi

#---------------------------------------------
# Set domains
#---------------------------------------------

is_domain() { [[ "$1" =~ ^([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$ ]]; }

[[ -n "$DOMAIN" ]] || DOMAIN=$(ask "Enter your app domain or sub.domain (e.g. meet.example.com)")
DOMAIN="${DOMAIN,,}"
is_domain "$DOMAIN" || error "Invalid or empty domain: '$DOMAIN'. Exiting..."

if [[ -z "$LIVEKIT_DOMAIN" ]]; then
    LIVEKIT_DOMAIN=$(ask "Enter your LiveKit domain or sub.domain [livekit.$DOMAIN]")
    LIVEKIT_DOMAIN="${LIVEKIT_DOMAIN:-livekit.$DOMAIN}"
fi
LIVEKIT_DOMAIN="${LIVEKIT_DOMAIN,,}"
is_domain "$LIVEKIT_DOMAIN" || error "Invalid LiveKit domain: '$LIVEKIT_DOMAIN'. Exiting..."
[[ "$LIVEKIT_DOMAIN" != "$DOMAIN" ]] || error "The LiveKit domain must be different from the app domain."

LETSENCRYPT_EMAIL="${LETSENCRYPT_EMAIL:-admin@$DOMAIN}"

[[ -n "$HOST_SIGN_IN" ]] || HOST_SIGN_IN=$(ask "Require host sign-in to start meetings (recommended on public servers)? [Y/n]")
if [[ "${HOST_SIGN_IN,,}" =~ ^(n|no|false|0)$ ]]; then HOST_SIGN_IN=false; else HOST_SIGN_IN=true; fi

#---------------------------------------------
# Install base packages
#---------------------------------------------

# Run all apt commands in non-interactive mode (no prompts)
export DEBIAN_FRONTEND=noninteractive

info "Updating package lists..."
apt-get update -y

info "Installing required system packages..."
apt-get install -y ca-certificates curl wget git openssl dnsutils

#---------------------------------------------
# Set Server Public IPv4
#---------------------------------------------

SERVER_IP="${SERVER_IP:-$(curl -4 -fsS --max-time 10 https://api.ipify.org || true)}"
[[ -n "$SERVER_IP" ]] || SERVER_IP=$(ask "Enter your SERVER public IPv4")
[[ "$SERVER_IP" =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}$ ]] || error "A valid server public IPv4 is required. Exiting..."

info "Server public IP: $SERVER_IP"

#---------------------------------------------
# Check that both domains point to this server
#---------------------------------------------

if [[ "$SKIP_DNS_CHECK" != "true" ]]; then
    for name in "$DOMAIN" "$LIVEKIT_DOMAIN"; do
        resolved=$(dig +short A "$name" | tail -n1)
        [[ -n "$resolved" ]] || error "Could not resolve $name. Add a DNS A record pointing to $SERVER_IP and try again."
        if [[ "$resolved" != "$SERVER_IP" ]]; then
            error "$name does NOT point to this server (expected $SERVER_IP, got $resolved).
        If it is behind a proxy/CDN on purpose, run again with SKIP_DNS_CHECK=true."
        fi
        info "$name points correctly to this server."
    done
else
    warning "Skipping the DNS check (SKIP_DNS_CHECK=true)."
fi

#---------------------------------------------
# Install Docker and Docker Compose
#---------------------------------------------

compose_version() { docker compose version --short 2>/dev/null | sed -E 's/^v//; s/[^0-9.].*$//' || true; }
version_ge() { [[ "$(printf '%s\n%s\n' "$2" "$1" | sort -V | head -n1)" == "$2" ]]; }

if command -v docker >/dev/null 2>&1 && [[ -n "$(compose_version)" ]] && version_ge "$(compose_version)" "$MIN_COMPOSE_VERSION"; then
    info "Docker already installed: $(docker --version), Compose $(compose_version)"
elif command -v docker >/dev/null 2>&1; then
    error "Docker is installed but Docker Compose >= $MIN_COMPOSE_VERSION is missing.
        Install the docker-compose-plugin (https://docs.docker.com/engine/install/ubuntu/) or use a fresh server."
else
    info "Installing Docker Engine and Docker Compose..."
    install -m 0755 -d /etc/apt/keyrings
    curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
    chmod a+r /etc/apt/keyrings/docker.asc
    echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu $(. /etc/os-release && echo "$VERSION_CODENAME") stable" \
        > /etc/apt/sources.list.d/docker.list
    apt-get update -y
    apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
    systemctl enable --now docker
    info "Installed $(docker --version), Compose $(compose_version)"
fi

#---------------------------------------------
# Clone MiroTalk LK repo
#---------------------------------------------

info "Cloning MiroTalk LK repository..."
git clone ${REPO_BRANCH:+--branch "$REPO_BRANCH"} "$REPO_URL" "$PROJECT_DIR"
cd "$PROJECT_DIR"

#---------------------------------------------
# Set environment
#---------------------------------------------

info "Setting up .env and generating secrets..."
cp .env.example .env
chmod 600 .env

# Sets KEY=VALUE in .env, uncommenting the key if it's there, appending it otherwise.
set_env() {
    if grep -qE "^#?[[:space:]]*$1=" .env; then
        sed -i -E "s|^#?[[:space:]]*$1=.*|$1=$2|" .env
    else
        echo "$1=$2" >> .env
    fi
}

LIVEKIT_API_KEY="API$(openssl rand -hex 6)"
LIVEKIT_API_SECRET="$(openssl rand -hex 32)"
SESSION_SECRET="$(openssl rand -hex 32)"

set_env NODE_ENV production
# Nginx on this machine reaches the app through Docker's published port (loopback / Docker network).
set_env TRUST_PROXY "loopback, uniquelocal"
set_env LIVEKIT_URL "wss://$LIVEKIT_DOMAIN"
set_env LIVEKIT_API_KEY "$LIVEKIT_API_KEY"
set_env LIVEKIT_API_SECRET "$LIVEKIT_API_SECRET"
set_env LIVEKIT_NODE_IP "$SERVER_IP"
set_env SESSION_SECRET "$SESSION_SECRET"
set_env OG_URL "https://$DOMAIN"

HOST_USER="admin"
HOST_PASSWORD=""
if [[ "$HOST_SIGN_IN" == "true" ]]; then
    HOST_PASSWORD="$(openssl rand -hex 12)"
    set_env HOST_USERS "$HOST_USER:$HOST_PASSWORD"
fi

#---------------------------------------------
# Keep LiveKit's API/WebSocket port local (Nginx proxies it)
#---------------------------------------------

# Docker's published ports bypass host firewalls such as ufw, so bind 7880 to 127.0.0.1 here.
cat > docker-compose.override.yml <<EOF
# Generated by lk-install.sh. Docker Compose loads it automatically next to docker-compose.yml.
# LiveKit signalling (7880) is only reachable through Nginx (wss://$LIVEKIT_DOMAIN);
# WebRTC media (7881/tcp, 7882/udp) stays public.
services:
    livekit:
        ports: !override
            - '127.0.0.1:$LIVEKIT_PORT:$LIVEKIT_PORT'
            - '7881:7881'
            - '7882:7882/udp'
EOF

# In-browser recording uploads (app user) and LiveKit Egress recordings (egress user) are written here.
mkdir -p recordings
chmod 777 recordings

#---------------------------------------------
# Build and start containers
#---------------------------------------------

info "Building and starting containers (first build may take a few minutes)..."
docker compose pull --ignore-buildable
docker compose up -d --build

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 "App is up on 127.0.0.1:$APP_PORT"

#---------------------------------------------
# Install Nginx and Certbot
#---------------------------------------------

info "Installing Nginx and Certbot..."
apt-get install -y nginx certbot
mkdir -p "$ACME_WEBROOT"

#---------------------------------------------
# HTTP: Let's Encrypt challenges + redirect to HTTPS
#---------------------------------------------

HTTP_SERVER=$(cat <<EOF
# HTTP: Let's Encrypt challenges, everything else redirects to HTTPS
server {
    listen 80;
    listen [::]:80;
    server_name $DOMAIN $LIVEKIT_DOMAIN;

    location /.well-known/acme-challenge/ {
        root $ACME_WEBROOT;
    }

    location / {
        return 301 https://\$host\$request_uri;
    }
}
EOF
)

info "Configuring Nginx for MiroTalk LK..."
echo "$HTTP_SERVER" > "$NGINX_SITE"
ln -sf "$NGINX_SITE" "$NGINX_SITE_ENABLED"
nginx -t
systemctl reload nginx || systemctl restart nginx

#---------------------------------------------
# Generate SSL certificate (both domains)
#---------------------------------------------

info "Generating SSL certificate with Certbot..."
certbot certonly --webroot -w "$ACME_WEBROOT" \
    --cert-name "$DOMAIN" -d "$DOMAIN" -d "$LIVEKIT_DOMAIN" \
    --non-interactive --agree-tos -m "$LETSENCRYPT_EMAIL" \
    --deploy-hook "systemctl reload nginx"

#---------------------------------------------
# HTTPS: proxy the app and LiveKit
#---------------------------------------------

cat > "$NGINX_SITE" <<EOF
# MiroTalk LK - generated by lk-install.sh

map \$http_upgrade \$mirotalk_lk_connection_upgrade {
    default upgrade;
    ''      close;
}

$HTTP_SERVER

# MiroTalk LK app
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name $DOMAIN;

    ssl_certificate /etc/letsencrypt/live/$DOMAIN/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/$DOMAIN/privkey.pem;

    # In-browser recordings are uploaded in 16 MB chunks.
    client_max_body_size 20m;

    # Prometheus metrics (METRICS_ENABLED) are for your monitoring network, not the internet.
    location = /metrics {
        return 404;
    }

    location / {
        proxy_pass http://127.0.0.1:$APP_PORT;
        proxy_http_version 1.1;
        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_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection \$mirotalk_lk_connection_upgrade;

        # Large headers/cookies from some single sign-on providers.
        proxy_buffer_size       128k;
        proxy_buffers         8 256k;
        proxy_busy_buffers_size 512k;
    }
}

# LiveKit signalling (WebSocket). Media goes directly to 7881/tcp and 7882/udp.
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name $LIVEKIT_DOMAIN;

    ssl_certificate /etc/letsencrypt/live/$DOMAIN/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/$DOMAIN/privkey.pem;

    location / {
        proxy_pass http://127.0.0.1:$LIVEKIT_PORT;
        proxy_http_version 1.1;
        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_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection \$mirotalk_lk_connection_upgrade;
        proxy_buffering off;
        proxy_read_timeout 86400s;
        proxy_send_timeout 86400s;
    }
}
EOF

nginx -t
systemctl reload nginx

#---------------------------------------------
# Firewall (only if ufw is already active)
#---------------------------------------------

if command -v ufw >/dev/null 2>&1 && ufw status | grep -q "Status: active"; then
    info "Opening firewall ports in ufw..."
    ufw allow 80/tcp
    ufw allow 443/tcp
    ufw allow 7881/tcp
    ufw allow 7882/udp
fi

#---------------------------------------------
# Check SSL auto-renewal
#---------------------------------------------

info "Checking SSL auto-renewal..."
certbot renew --dry-run --cert-name "$DOMAIN" || warning "Certificate renewal dry run failed; check 'certbot renew --dry-run'."

#---------------------------------------------
# Done
#---------------------------------------------

echo ""
info "MiroTalk LK installation complete!"
info "Access your instance at \e[32mhttps://$DOMAIN\e[0m"
info "LiveKit signalling at \e[32mwss://$LIVEKIT_DOMAIN\e[0m"
echo ""
if [[ "$HOST_SIGN_IN" == "true" ]]; then
    info "Host sign-in (click 'Host sign in' in the lobby):"
    echo -e "  Username: \e[33m$HOST_USER\e[0m"
    echo -e "  Password: \e[33m$HOST_PASSWORD\e[0m"
    echo ""
fi
info "LiveKit API credentials:"
echo -e "  LIVEKIT_API_KEY:    \e[33m$LIVEKIT_API_KEY\e[0m"
echo -e "  LIVEKIT_API_SECRET: \e[33m$LIVEKIT_API_SECRET\e[0m"
echo ""
warning "Save these secrets securely. They are stored in $PROJECT_DIR/.env"
warning "If your cloud provider has its own firewall, open 80/tcp, 443/tcp, 7881/tcp and 7882/udp there too."
info "Recording and live captions are off by default: see the self-hosting guide to enable them."
