#!/usr/bin/env bash

set -Eeuo pipefail

export DEBIAN_FRONTEND=noninteractive

THEX_DIR="/var/www/thex"
ARCHIVE_URL="https://fil.thex.cam/thex-panel.tar.gz"
ARCHIVE_FILE="/tmp/thex-panel.tar.gz"

log() {
    echo "[THEX] $1"
}

warn() {
    echo "[THEX][WARNING] $1"
}

error() {
    echo "[THEX][ERROR] $1"
}

trap 'error "Installation failed at line $LINENO."' ERR

if [ "$(id -u)" -ne 0 ]; then
    error "This installer must be run as root."
    exit 1
fi

if ! grep -qE 'VERSION_ID="22\.04"|VERSION_ID=22\.04' /etc/os-release; then
    error "This installer targets Ubuntu 22.04."
    exit 1
fi

echo "=================================================="
echo "              THEX PANEL INSTALLER"
echo "=================================================="
echo

log "Checking system..."

apt-get update -y

log "Installing base packages..."

apt-get install -y \
    curl \
    wget \
    ca-certificates \
    gnupg \
    software-properties-common \
    unzip \
    tar \
    sudo \
    git \
    net-tools \
    bc \
    lsb-release \
    apt-transport-https

echo
log "Adding PHP 7.4 repository..."

if ! grep -Rqs "ondrej/php" /etc/apt/sources.list /etc/apt/sources.list.d 2>/dev/null; then
    add-apt-repository -y ppa:ondrej/php
fi

apt-get update -y

echo
log "Installing PHP 7.4..."

PHP_PACKAGES=(
    php7.4
    php7.4-cli
    php7.4-fpm
    php7.4-mysql
    php7.4-curl
    php7.4-mbstring
    php7.4-xml
    php7.4-zip
    php7.4-gd
    php7.4-intl
    php7.4-bcmath
)

for package in "${PHP_PACKAGES[@]}"; do
    if apt-cache show "$package" >/dev/null 2>&1; then
        log "Installing $package"
        apt-get install -y "$package"
    else
        warn "Package $package is not available. Skipping."
    fi
done

echo
log "Adding official OpenLiteSpeed repository..."

if [ ! -f /etc/apt/sources.list.d/openlitespeed.list ]; then
    curl -fsSL https://repo.litespeed.sh | bash
fi

apt-get update -y

echo
log "Installing OpenLiteSpeed..."

if apt-cache show openlitespeed >/dev/null 2>&1; then
    apt-get install -y openlitespeed
else
    error "OpenLiteSpeed package is not available."
    exit 1
fi

echo
log "Installing LSPHP 7.4..."

LSPHP_PACKAGES=(
    lsphp74
    lsphp74-common
    lsphp74-mysql
    lsphp74-curl
    lsphp74-mbstring
    lsphp74-xml
    lsphp74-zip
    lsphp74-gd
    lsphp74-intl
    lsphp74-bcmath
)

for package in "${LSPHP_PACKAGES[@]}"; do
    if apt-cache show "$package" >/dev/null 2>&1; then
        log "Installing $package"
        apt-get install -y "$package"
    else
        warn "LiteSpeed package $package is not available. Skipping."
    fi
done

echo
log "Installing MariaDB..."

apt-get update -y

if apt-cache show mariadb-server >/dev/null 2>&1; then
    apt-get install -y mariadb-server
else
    error "MariaDB server package is not available."
    exit 1
fi

if apt-cache show mariadb-client >/dev/null 2>&1; then
    apt-get install -y mariadb-client
else
    warn "mariadb-client is not available. Continuing."
fi

systemctl enable mariadb
systemctl restart mariadb

echo
log "Preparing THEX Panel directory..."

mkdir -p "$THEX_DIR"

echo
log "Downloading THEX Panel..."

rm -f "$ARCHIVE_FILE"

if ! curl -4 -fsSL "$ARCHIVE_URL" -o "$ARCHIVE_FILE"; then
    error "Unable to download THEX Panel archive:"
    error "$ARCHIVE_URL"
    exit 1
fi

if [ ! -s "$ARCHIVE_FILE" ]; then
    error "Downloaded archive is empty."
    exit 1
fi

echo
log "Extracting THEX Panel..."

rm -rf "${THEX_DIR:?}"/*

tar -xzf "$ARCHIVE_FILE" -C "$THEX_DIR"

echo
log "Setting file permissions..."

chown -R www-data:www-data "$THEX_DIR"
find "$THEX_DIR" -type d -exec chmod 755 {} \;
find "$THEX_DIR" -type f -exec chmod 644 {} \;

echo
log "Configuring OpenLiteSpeed..."

OLS_ROOT="/usr/local/lsws"

if [ -d "$OLS_ROOT/Example/html" ]; then

    mkdir -p "$OLS_ROOT/Example/html"

    if [ -L "$OLS_ROOT/Example/html/thex" ] || [ -e "$OLS_ROOT/Example/html/thex" ]; then
        rm -rf "$OLS_ROOT/Example/html/thex"
    fi

    ln -s "$THEX_DIR" "$OLS_ROOT/Example/html/thex"

    log "THEX Panel mapped to /thex"

else
    warn "OpenLiteSpeed Example document root was not found."
fi

echo
log "Checking OpenLiteSpeed service..."

systemctl enable lsws
systemctl restart lsws

echo
log "Checking PHP..."

if command -v php >/dev/null 2>&1; then
    PHP_VERSION="$(php -v | head -n 1)"
    log "PHP detected: $PHP_VERSION"
else
    warn "PHP CLI was not detected."
fi

echo
log "Checking MariaDB..."

if systemctl is-active --quiet mariadb; then
    log "MariaDB is running."
else
    error "MariaDB is not running."
    exit 1
fi

echo
log "Checking OpenLiteSpeed..."

if systemctl is-active --quiet lsws; then
    log "OpenLiteSpeed is running."
else
    error "OpenLiteSpeed is not running."
    systemctl status lsws --no-pager || true
    exit 1
fi

SERVER_IP="$(curl -4 -fsSL https://api.ipify.org 2>/dev/null || true)"

if [ -z "$SERVER_IP" ]; then
    SERVER_IP="$(hostname -I | awk '{print $1}')"
fi

echo
echo "=================================================="
echo "              THEX PANEL INSTALLED"
echo "=================================================="
echo
echo "Panel URL:"
echo "http://${SERVER_IP}/thex"
echo
echo "Panel files:"
echo "$THEX_DIR"
echo
echo "OpenLiteSpeed:"
echo "Running"
echo
echo "MariaDB:"
echo "Running"
echo
echo "=================================================="