#!/usr/bin/env bash
# setup-element.sh — descargar y servir Element Web localmente
set -euo pipefail

ELEMENT_VERSION="v1.11.92"
ELEMENT_DIR="$(cd "$(dirname "$0")/.." && pwd)/element-web"
PORT="${ELEMENT_PORT:-8090}"
PIDFILE="$ELEMENT_DIR/.server.pid"
HOMESERVER="${MATRIX_HOMESERVER:-https://matrix-af2f3d.organic-machine.com}"
SERVER_NAME="${MATRIX_SERVER_NAME:-matrix-af2f3d.organic-machine.com}"

usage() {
    echo "Uso: $0 {start|stop|status}"
    echo ""
    echo "  start   Descargar Element Web (si falta) y servir en puerto $PORT"
    echo "  stop    Detener el servidor local"
    echo "  status  Verificar si el servidor esta corriendo"
    exit 1
}

download_element() {
    if [ -d "$ELEMENT_DIR" ] && [ -f "$ELEMENT_DIR/index.html" ]; then
        echo "Element Web ya descargado en $ELEMENT_DIR"
        return 0
    fi

    local tarball="element-${ELEMENT_VERSION}.tar.gz"
    local url="https://github.com/element-hq/element-web/releases/download/${ELEMENT_VERSION}/element-${ELEMENT_VERSION}.tar.gz"

    echo "Descargando Element Web ${ELEMENT_VERSION}..."
    mkdir -p "$ELEMENT_DIR"
    curl -fSL "$url" -o "/tmp/$tarball"
    tar xzf "/tmp/$tarball" --strip-components=1 -C "$ELEMENT_DIR"
    rm -f "/tmp/$tarball"

    echo "Generando config.json para homeserver $HOMESERVER..."
    cat > "$ELEMENT_DIR/config.json" <<CONF
{
    "default_server_config": {
        "m.homeserver": {
            "base_url": "$HOMESERVER",
            "server_name": "$SERVER_NAME"
        }
    },
    "brand": "Element",
    "disable_guests": true,
    "disable_3pid_login": true
}
CONF

    echo "Element Web ${ELEMENT_VERSION} listo en $ELEMENT_DIR"
}

start_server() {
    if [ -f "$PIDFILE" ] && kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then
        echo "Element Web ya corriendo (PID $(cat "$PIDFILE")) en http://localhost:$PORT"
        return 0
    fi

    download_element

    echo "Iniciando servidor en http://localhost:$PORT ..."
    if command -v python3 &>/dev/null; then
        (cd "$ELEMENT_DIR" && python3 -m http.server "$PORT" --bind 0.0.0.0) &>/dev/null &
    elif command -v npx &>/dev/null; then
        npx --yes serve -s "$ELEMENT_DIR" -l "$PORT" &>/dev/null &
    else
        echo "Error: necesitas python3 o npx (Node.js) para servir archivos"
        exit 1
    fi

    echo $! > "$PIDFILE"

    # Esperar a que el servidor arranque
    for i in 1 2 3 4 5; do
        if curl -sf "http://localhost:$PORT/" >/dev/null 2>&1; then
            echo "Element Web serving en http://localhost:$PORT (PID $!)"
            return 0
        fi
        sleep 1
    done
    echo "WARN: servidor iniciado (PID $!) pero no responde aun en http://localhost:$PORT"
}

stop_server() {
    if [ ! -f "$PIDFILE" ]; then
        echo "No hay servidor corriendo (no se encontro pidfile)"
        return 0
    fi

    local pid
    pid=$(cat "$PIDFILE")
    if kill -0 "$pid" 2>/dev/null; then
        kill "$pid"
        echo "Servidor detenido (PID $pid)"
    else
        echo "Proceso $pid ya no existe"
    fi
    rm -f "$PIDFILE"
}

server_status() {
    if [ -f "$PIDFILE" ] && kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then
        echo "Element Web corriendo (PID $(cat "$PIDFILE")) en http://localhost:$PORT"
    else
        echo "Element Web no esta corriendo"
        [ -f "$PIDFILE" ] && rm -f "$PIDFILE"
    fi
}

case "${1:-}" in
    start)  start_server ;;
    stop)   stop_server ;;
    status) server_status ;;
    *)      usage ;;
esac
