#!/usr/bin/env bash

set -Eeuo pipefail

# ============================================================
# Phoenix AWR Installer for Linux
#
# Runtime oficial:
# - Publicado por MC3D
# - Java 21
# - Incluye JavaFX
# - Se descarga siempre
#
# No utiliza automáticamente:
# - JAVA_HOME del sistema
# - /usr/bin/java
# - JVM instalada por Fedora, Ubuntu u otra distribución
#
# Compatible con:
# - Cinnamon
# - GNOME
# - KDE Plasma
# - Xfce
# - MATE
# - LXQt
# - Budgie
# - Otros escritorios compatibles con XDG/FreeDesktop
#
# Arquitectura:
# - Linux x86_64
# ============================================================

# ============================================================
# Identidad de Phoenix AWR
# ============================================================

APP_NAME="Phoenix AWR"
APP_ID="cl.mc3d.phoenixawr"

URI_SCHEME="phoenixawr"
URI_MIME="x-scheme-handler/$URI_SCHEME"

DESKTOP_FILENAME="phoenixawr.desktop"

# ============================================================
# Directorios XDG
# ============================================================

XDG_DATA_HOME_EFFECTIVE="${XDG_DATA_HOME:-$HOME/.local/share}"
XDG_CONFIG_HOME_EFFECTIVE="${XDG_CONFIG_HOME:-$HOME/.config}"

BASE="$XDG_DATA_HOME_EFFECTIVE/PhoenixApplet"

APPLICATION_DIR="$BASE/application"
RUNTIME_DIR="$BASE/runtime/bundled"
BIN_DIR="$BASE/bin"
LOG_DIR="$BASE/logs"

APPLICATIONS_DIR="$XDG_DATA_HOME_EFFECTIVE/applications"
ICONS_BASE_DIR="$XDG_DATA_HOME_EFFECTIVE/icons/hicolor"

JVM_CONF="$BASE/jvm.conf"

INSTALL_LOG="$LOG_DIR/phoenix-installer.log"
PROTOCOL_LOG="$LOG_DIR/phoenixawr-protocol.log"
STARTUP_LOG="$LOG_DIR/phoenixawr-startup.log"

LAUNCHER="$BIN_DIR/phoenixawr"
DESKTOP_FILE="$APPLICATIONS_DIR/$DESKTOP_FILENAME"

# ============================================================
# Descargas oficiales publicadas por MC3D
# ============================================================

OFFICIAL_RUNTIME_URL="https://www.mc3d.cl/documents/d/guest/zulu21-44-17-ca-fx-jre21-0-8-linux_x64-tar"

PHOENIX_APPLICATION_URL="https://www.mc3d.cl/documents/d/guest/applet_viewer_by_mc3d"

TEMP_DIR="${TMPDIR:-/tmp}/phoenixawr-installer-$$"

RUNTIME_ARCHIVE="$TEMP_DIR/phoenixawr-runtime.tar.gz"
APPLICATION_ARCHIVE="$TEMP_DIR/phoenixawr-application.zip"

# ============================================================
# Nombres históricos que deben eliminarse
# ============================================================

OLD_DESKTOP_FILES=(
    "phoenixawr.desktop"
    "phoenixappletrunner.desktop"
    "phoenix-applet-viewer.desktop"
    "PhoenixAWR.desktop"
    "PhoenixApplet.desktop"
    "Phoenix Applet Viewer.desktop"
    "Phoenix AWR.desktop"
)

OLD_NATIVE_HOST_FILES=(
    "phoenixappletrunner.json"
    "phoenixawr.json"
    "cl.mc3d.phoenixawr.json"
    "cl.mc3d.phoenixappletrunner.json"
)

# ============================================================
# Funciones generales
# ============================================================

log() {
    local message="$1"

    printf '%s\n' "$message"

    if [ -d "$LOG_DIR" ]; then
        printf '%s\n' "$message" >> "$INSTALL_LOG"
    fi
}

fail() {
    log "[ERROR] $1"
    exit 1
}

command_exists() {
    command -v "$1" >/dev/null 2>&1
}

cleanup_temporary_files() {
    rm -rf "$TEMP_DIR"
}

trap cleanup_temporary_files EXIT

handle_error() {
    local exit_code=$?
    local line_number="${1:-unknown}"

    log "[ERROR] Installation failed at line $line_number."
    exit "$exit_code"
}

trap 'handle_error $LINENO' ERR

download_file() {
    local url="$1"
    local destination="$2"

    rm -f "$destination"

    if command_exists curl; then
        log "[INFO] Downloading with curl..."

        curl \
            --fail \
            --location \
            --show-error \
            --connect-timeout 30 \
            --retry 3 \
            --retry-delay 2 \
            --output "$destination" \
            "$url"

    elif command_exists wget; then
        log "[INFO] Downloading with wget..."

        wget \
            --tries=3 \
            --timeout=30 \
            --output-document="$destination" \
            "$url"

    else
        fail "curl or wget is required."
    fi

    if [ ! -s "$destination" ]; then
        fail "Downloaded file is empty: $destination"
    fi
}

remove_path() {
    local path="$1"

    if [ -e "$path" ] || [ -L "$path" ]; then
        rm -rf "$path"
        log "[INFO] Removed: $path"
    fi
}

remove_native_hosts_from_directory() {
    local directory="$1"
    local filename

    for filename in "${OLD_NATIVE_HOST_FILES[@]}"; do
        remove_path "$directory/$filename"
    done
}

get_desktop_directory() {
    local desktop_directory=""

    if command_exists xdg-user-dir; then
        desktop_directory="$(xdg-user-dir DESKTOP 2>/dev/null || true)"
    fi

    if [ -z "$desktop_directory" ] ||
       [ "$desktop_directory" = "$HOME" ]; then

        if [ -d "$HOME/Escritorio" ]; then
            desktop_directory="$HOME/Escritorio"
        else
            desktop_directory="$HOME/Desktop"
        fi
    fi

    printf '%s' "$desktop_directory"
}

escape_desktop_exec_path() {
    local value="$1"

    value="${value//\\/\\\\}"
    value="${value//\"/\\\"}"

    printf '%s' "$value"
}

# ============================================================
# Validación del sistema
# ============================================================

if [ "$(uname -s)" != "Linux" ]; then
    fail "This installer is intended for Linux."
fi

ARCHITECTURE="$(uname -m)"

case "$ARCHITECTURE" in
    x86_64|amd64)
        ;;
    *)
        fail "The official Phoenix AWR runtime requires x86_64. Detected architecture: $ARCHITECTURE"
        ;;
esac

command_exists tar ||
    fail "tar is required."

command_exists unzip ||
    fail "unzip is required."

command_exists find ||
    fail "find is required."

command_exists sed ||
    fail "sed is required."

command_exists grep ||
    fail "grep is required."

command_exists xdg-mime ||
    fail "xdg-mime is required. Install the xdg-utils package."

mkdir -p "$TEMP_DIR"

# ============================================================
# Inicio
# ============================================================

echo
echo "============================================================"
echo " Phoenix AWR Linux Installer"
echo "============================================================"
echo

echo "[INFO] Phoenix AWR will install its official MC3D runtime."
echo "[INFO] The runtime includes JavaFX."
echo "[INFO] The operating system JVM will not be used."
echo

DESKTOP_DIR="$(get_desktop_directory)"

# ============================================================
# Limpieza del manejador de protocolo anterior
# ============================================================

CURRENT_HANDLER="$(
    xdg-mime query default "$URI_MIME" 2>/dev/null || true
)"

if [ -n "$CURRENT_HANDLER" ]; then
    case "$CURRENT_HANDLER" in
        phoenixawr.desktop|\
        phoenixappletrunner.desktop|\
        phoenix-applet-viewer.desktop|\
        PhoenixAWR.desktop|\
        PhoenixApplet.desktop)
            log "[INFO] Previous Phoenix AWR protocol handler detected: $CURRENT_HANDLER"
            ;;
    esac
fi

# ============================================================
# Limpieza de accesos directos antiguos
# ============================================================

log "[INFO] Cleaning previous Phoenix AWR desktop entries..."

for desktop_name in "${OLD_DESKTOP_FILES[@]}"; do
    remove_path "$APPLICATIONS_DIR/$desktop_name"
    remove_path "$DESKTOP_DIR/$desktop_name"
done

remove_path "$DESKTOP_DIR/PhoenixAWR"
remove_path "$DESKTOP_DIR/PhoenixApplet"
remove_path "$DESKTOP_DIR/Phoenix AWR"
remove_path "$DESKTOP_DIR/PhoenixAppletViewer"

# ============================================================
# Limpieza de Native Messaging
# ============================================================

log "[INFO] Removing obsolete Native Messaging registrations..."

# Firefox
remove_native_hosts_from_directory \
    "$HOME/.mozilla/native-messaging-hosts"

# Google Chrome
remove_native_hosts_from_directory \
    "$XDG_CONFIG_HOME_EFFECTIVE/google-chrome/NativeMessagingHosts"

remove_native_hosts_from_directory \
    "$XDG_CONFIG_HOME_EFFECTIVE/google-chrome-beta/NativeMessagingHosts"

remove_native_hosts_from_directory \
    "$XDG_CONFIG_HOME_EFFECTIVE/google-chrome-unstable/NativeMessagingHosts"

# Chromium
remove_native_hosts_from_directory \
    "$XDG_CONFIG_HOME_EFFECTIVE/chromium/NativeMessagingHosts"

remove_native_hosts_from_directory \
    "$XDG_CONFIG_HOME_EFFECTIVE/chromium-browser/NativeMessagingHosts"

# Microsoft Edge
remove_native_hosts_from_directory \
    "$XDG_CONFIG_HOME_EFFECTIVE/microsoft-edge/NativeMessagingHosts"

remove_native_hosts_from_directory \
    "$XDG_CONFIG_HOME_EFFECTIVE/microsoft-edge-beta/NativeMessagingHosts"

remove_native_hosts_from_directory \
    "$XDG_CONFIG_HOME_EFFECTIVE/microsoft-edge-dev/NativeMessagingHosts"

# Brave
remove_native_hosts_from_directory \
    "$XDG_CONFIG_HOME_EFFECTIVE/BraveSoftware/Brave-Browser/NativeMessagingHosts"

remove_native_hosts_from_directory \
    "$XDG_CONFIG_HOME_EFFECTIVE/BraveSoftware/Brave-Browser-Beta/NativeMessagingHosts"

remove_native_hosts_from_directory \
    "$XDG_CONFIG_HOME_EFFECTIVE/BraveSoftware/Brave-Browser-Nightly/NativeMessagingHosts"

# Vivaldi
remove_native_hosts_from_directory \
    "$XDG_CONFIG_HOME_EFFECTIVE/vivaldi/NativeMessagingHosts"

remove_native_hosts_from_directory \
    "$XDG_CONFIG_HOME_EFFECTIVE/vivaldi-snapshot/NativeMessagingHosts"

# Opera
remove_native_hosts_from_directory \
    "$XDG_CONFIG_HOME_EFFECTIVE/opera/NativeMessagingHosts"

remove_native_hosts_from_directory \
    "$XDG_CONFIG_HOME_EFFECTIVE/opera-developer/NativeMessagingHosts"

# ============================================================
# Limpieza de iconos anteriores
# ============================================================

log "[INFO] Removing previous Phoenix AWR icons..."

for size in 16 22 24 32 36 48 64 72 96 128 192 256 384 512; do
    remove_path \
        "$ICONS_BASE_DIR/${size}x${size}/apps/phoenixawr.png"

    remove_path \
        "$ICONS_BASE_DIR/${size}x${size}/apps/$APP_ID.png"
done

remove_path "$ICONS_BASE_DIR/scalable/apps/phoenixawr.svg"
remove_path "$ICONS_BASE_DIR/scalable/apps/$APP_ID.svg"

# ============================================================
# Limpieza de la instalación anterior
# ============================================================

log "[INFO] Removing previous Phoenix AWR installation..."

remove_path "$BASE"

mkdir -p "$APPLICATION_DIR"
mkdir -p "$RUNTIME_DIR"
mkdir -p "$BIN_DIR"
mkdir -p "$LOG_DIR"
mkdir -p "$APPLICATIONS_DIR"
mkdir -p "$DESKTOP_DIR"

touch "$INSTALL_LOG"

log "[INFO] Clean installation directory created:"
log "[INFO] $BASE"

# ============================================================
# Descarga del runtime oficial MC3D
# ============================================================

log "[INFO] Downloading the official Phoenix AWR runtime published by MC3D..."
log "[INFO] This runtime includes JavaFX."
log "[INFO] The system JVM is intentionally ignored."

download_file \
    "$OFFICIAL_RUNTIME_URL" \
    "$RUNTIME_ARCHIVE"

if ! tar -tzf "$RUNTIME_ARCHIVE" >/dev/null 2>&1; then
    fail "The official runtime download is not a valid gzip tar archive."
fi

log "[INFO] Extracting the official Phoenix AWR runtime..."

tar -xzf "$RUNTIME_ARCHIVE" -C "$RUNTIME_DIR"

JAVA_EXECUTABLE="$(
    find "$RUNTIME_DIR" \
        -type f \
        -path '*/bin/java' \
        2>/dev/null |
    head -n 1
)"

if [ -z "$JAVA_EXECUTABLE" ]; then
    fail "Java was not found inside the official Phoenix AWR runtime."
fi

chmod 755 "$JAVA_EXECUTABLE"

JAVA_BIN_DIRECTORY="$(dirname "$JAVA_EXECUTABLE")"
BUNDLED_JAVA_HOME="$(dirname "$JAVA_BIN_DIRECTORY")"

if [ ! -x "$BUNDLED_JAVA_HOME/bin/java" ]; then
    fail "The official Phoenix AWR runtime is not executable."
fi

# ============================================================
# Validación de JavaFX
# ============================================================

log "[INFO] Validating JavaFX modules..."

JAVA_MODULES="$(
    "$BUNDLED_JAVA_HOME/bin/java" \
        --list-modules \
        2>/dev/null || true
)"

if [ -z "$JAVA_MODULES" ]; then
    fail "The official Phoenix AWR runtime could not list its modules."
fi

if ! printf '%s\n' "$JAVA_MODULES" |
    grep -q '^javafx\.base@'; then

    fail "The official Phoenix AWR runtime does not contain javafx.base."
fi

if ! printf '%s\n' "$JAVA_MODULES" |
    grep -q '^javafx\.graphics@'; then

    fail "The official Phoenix AWR runtime does not contain javafx.graphics."
fi

if ! printf '%s\n' "$JAVA_MODULES" |
    grep -q '^javafx\.controls@'; then

    fail "The official Phoenix AWR runtime does not contain javafx.controls."
fi

if ! printf '%s\n' "$JAVA_MODULES" |
    grep -q '^javafx\.media@'; then

    fail "The official Phoenix AWR runtime does not contain javafx.media."
fi

if ! printf '%s\n' "$JAVA_MODULES" |
    grep -q '^javafx\.web@'; then

    fail "The official Phoenix AWR runtime does not contain javafx.web."
fi

log "[INFO] JavaFX validation completed successfully."

# ============================================================
# Configuración del runtime
# ============================================================

cat > "$JVM_CONF" <<EOF
# ============================================================
# Phoenix AWR official runtime configuration
# ============================================================
#
# Phoenix AWR always installs and uses the official runtime
# published by MC3D.
#
# This runtime includes JavaFX.
#
# The operating system JVM is intentionally ignored.
#
# Phoenix AWR is the main application.
# Java is only the internal runtime used to start Phoenix AWR.
#
runtime_mode=bundled
runtime_vendor=MC3D
runtime_includes_javafx=true
java_home=$BUNDLED_JAVA_HOME
EOF

chmod 644 "$JVM_CONF"

log "[INFO] Phoenix AWR runtime configuration created:"
log "[INFO] $JVM_CONF"

# ============================================================
# Descarga de Phoenix AWR
# ============================================================

log "[INFO] Downloading Phoenix AWR..."

download_file \
    "$PHOENIX_APPLICATION_URL" \
    "$APPLICATION_ARCHIVE"

if ! unzip -tq "$APPLICATION_ARCHIVE" >/dev/null 2>&1; then
    fail "The Phoenix AWR application download is not a valid ZIP archive."
fi

log "[INFO] Extracting Phoenix AWR..."

unzip -q -o \
    "$APPLICATION_ARCHIVE" \
    -d "$APPLICATION_DIR"

PHOENIX_JAR="$(
    find "$APPLICATION_DIR" \
        -type f \
        -iname 'PhoenixAppletViewer.jar' \
        2>/dev/null |
    head -n 1
)"

if [ -z "$PHOENIX_JAR" ]; then
    fail "PhoenixAppletViewer.jar was not found after extraction."
fi

log "[INFO] Phoenix AWR application located:"
log "[INFO] $PHOENIX_JAR"

# ============================================================
# Eliminación interna de Native Messaging
# ============================================================

log "[INFO] Removing Native Messaging files from the Phoenix package..."

find "$APPLICATION_DIR" \
    -type f \
    \( \
        -iname 'phoenixappletrunner*.json' \
        -o -iname 'phoenixawr*.json' \
        -o -iname 'register_plugin_linux*.sh' \
        -o -iname 'register_native*.sh' \
        -o -iname 'phoenixappletrunner.sh' \
        -o -iname '*native*messaging*.sh' \
    \) \
    -delete 2>/dev/null || true

log "[INFO] Obsolete Native Messaging components removed."

# ============================================================
# Búsqueda del icono oficial
# ============================================================

log "[INFO] Searching for the official Phoenix AWR icon..."

OFFICIAL_ICON_SVG="$(
    find "$APPLICATION_DIR" \
        -type f \
        \( \
            -iname 'phoenixawr.svg' \
            -o -iname 'phoenix-awr.svg' \
            -o -iname 'phoenix_awr.svg' \
            -o -iname '*phoenix*awr*.svg' \
        \) \
        2>/dev/null |
    head -n 1
)"

OFFICIAL_ICON_PNG="$(
    find "$APPLICATION_DIR" \
        -type f \
        \( \
            -iname 'phoenixawr.png' \
            -o -iname 'phoenix-awr.png' \
            -o -iname 'phoenix_awr.png' \
            -o -iname '*phoenix*awr*.png' \
        \) \
        2>/dev/null |
    head -n 1
)"

OFFICIAL_ICON_ICO="$(
    find "$APPLICATION_DIR" \
        -type f \
        \( \
            -iname 'phoenixawr.ico' \
            -o -iname 'phoenix-awr.ico' \
            -o -iname '*phoenix*awr*.ico' \
        \) \
        2>/dev/null |
    head -n 1
)"

# ============================================================
# Icono de respaldo
# ============================================================

if [ -z "$OFFICIAL_ICON_SVG" ] &&
   [ -z "$OFFICIAL_ICON_PNG" ] &&
   [ -z "$OFFICIAL_ICON_ICO" ]; then

    log "[WARNING] No official Phoenix AWR icon was found in the package."
    log "[INFO] Creating a temporary fallback icon."

    OFFICIAL_ICON_SVG="$BASE/phoenixawr-fallback.svg"

    cat > "$OFFICIAL_ICON_SVG" <<'EOF'
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg"
     width="512"
     height="512"
     viewBox="0 0 512 512">

    <defs>
        <linearGradient id="background"
                        x1="0"
                        y1="0"
                        x2="1"
                        y2="1">
            <stop offset="0"
                  stop-color="#68120d"/>

            <stop offset="0.55"
                  stop-color="#d83a16"/>

            <stop offset="1"
                  stop-color="#ff9b1d"/>
        </linearGradient>
    </defs>

    <rect x="20"
          y="20"
          width="472"
          height="472"
          rx="104"
          fill="url(#background)"/>

    <path d="M256 77
             C204 120 173 166 169 222
             C165 277 189 322 224 363
             C236 377 247 392 256 412
             C265 392 276 377 288 363
             C323 322 347 277 343 222
             C339 166 308 120 256 77Z"
          fill="#ffffff"
          opacity="0.16"/>

    <path d="M145 348
             C180 314 202 287 226 257
             C199 251 179 232 168 204
             C210 209 239 226 253 253
             C261 211 289 177 347 145
             C334 208 308 254 270 284
             C305 280 337 289 369 316
             C324 326 290 321 262 303
             C236 332 202 349 145 348Z"
          fill="#ffffff"/>

    <text x="256"
          y="440"
          text-anchor="middle"
          font-family="sans-serif"
          font-size="54"
          font-weight="700"
          fill="#ffffff">
        AWR
    </text>
</svg>
EOF
fi

# ============================================================
# Instalación del icono SVG
# ============================================================

if [ -n "$OFFICIAL_ICON_SVG" ]; then
    mkdir -p "$ICONS_BASE_DIR/scalable/apps"

    cp -f \
        "$OFFICIAL_ICON_SVG" \
        "$ICONS_BASE_DIR/scalable/apps/phoenixawr.svg"

    chmod 644 \
        "$ICONS_BASE_DIR/scalable/apps/phoenixawr.svg"
fi

# ============================================================
# Instalación del icono PNG
# ============================================================

if [ -n "$OFFICIAL_ICON_PNG" ]; then
    mkdir -p "$ICONS_BASE_DIR/256x256/apps"

    cp -f \
        "$OFFICIAL_ICON_PNG" \
        "$ICONS_BASE_DIR/256x256/apps/phoenixawr.png"

    chmod 644 \
        "$ICONS_BASE_DIR/256x256/apps/phoenixawr.png"
fi

# ============================================================
# Conversión desde ICO
# ============================================================

if [ -z "$OFFICIAL_ICON_PNG" ] &&
   [ -n "$OFFICIAL_ICON_ICO" ] &&
   command_exists convert; then

    mkdir -p "$ICONS_BASE_DIR/256x256/apps"

    convert \
        "$OFFICIAL_ICON_ICO[0]" \
        -resize 256x256 \
        "$ICONS_BASE_DIR/256x256/apps/phoenixawr.png"

    OFFICIAL_ICON_PNG="$ICONS_BASE_DIR/256x256/apps/phoenixawr.png"
fi

# ============================================================
# Generación de tamaños PNG XDG
# ============================================================

ICON_SIZES=(
    16
    22
    24
    32
    36
    48
    64
    72
    96
    128
    192
    256
    384
    512
)

if [ -n "$OFFICIAL_ICON_SVG" ] &&
   command_exists rsvg-convert; then

    for size in "${ICON_SIZES[@]}"; do
        icon_directory="$ICONS_BASE_DIR/${size}x${size}/apps"
        icon_file="$icon_directory/phoenixawr.png"

        mkdir -p "$icon_directory"

        rsvg-convert \
            --width "$size" \
            --height "$size" \
            --output "$icon_file" \
            "$OFFICIAL_ICON_SVG"

        chmod 644 "$icon_file"
    done

elif [ -n "$OFFICIAL_ICON_PNG" ] &&
     command_exists convert; then

    for size in "${ICON_SIZES[@]}"; do
        icon_directory="$ICONS_BASE_DIR/${size}x${size}/apps"
        icon_file="$icon_directory/phoenixawr.png"

        mkdir -p "$icon_directory"

        convert \
            "$OFFICIAL_ICON_PNG" \
            -resize "${size}x${size}" \
            "$icon_file"

        chmod 644 "$icon_file"
    done
fi

if command_exists gtk-update-icon-cache; then
    gtk-update-icon-cache \
        --force \
        --ignore-theme-index \
        "$ICONS_BASE_DIR" \
        >/dev/null 2>&1 || true
fi

log "[INFO] Phoenix AWR icon installed."

# ============================================================
# Creación del lanzador principal
# ============================================================

log "[INFO] Creating the Phoenix AWR launcher..."

cat > "$LAUNCHER" <<EOF
#!/usr/bin/env bash

set -Eeuo pipefail

BASE="$BASE"
JVM_CONF="$JVM_CONF"
PHOENIX_JAR="$PHOENIX_JAR"
LOG_FILE="$PROTOCOL_LOG"

log() {
    printf '[%s] %s\n' \
        "\$(date '+%Y-%m-%d %H:%M:%S')" \
        "\$1" >> "\$LOG_FILE"
}

show_error() {
    local message="\$1"

    log "ERROR: \$message"

    if command -v zenity >/dev/null 2>&1; then
        zenity \
            --error \
            --title="Phoenix AWR" \
            --width=440 \
            --text="\$message" \
            2>/dev/null || true

    elif command -v kdialog >/dev/null 2>&1; then
        kdialog \
            --error "\$message" \
            --title "Phoenix AWR" \
            2>/dev/null || true

    else
        printf '%s\n' "\$message" >&2
    fi
}

if [ ! -f "\$JVM_CONF" ]; then
    show_error "The official Phoenix AWR runtime configuration was not found.

Please reinstall Phoenix AWR."
    exit 1
fi

RUNTIME_MODE="\$(
    sed -n \
        's/^[[:space:]]*runtime_mode[[:space:]]*=[[:space:]]*//p' \
        "\$JVM_CONF" |
    head -n 1
)"

JAVA_HOME="\$(
    sed -n \
        's/^[[:space:]]*java_home[[:space:]]*=[[:space:]]*//p' \
        "\$JVM_CONF" |
    head -n 1
)"

JAVA_HOME="\${JAVA_HOME%\\"}"
JAVA_HOME="\${JAVA_HOME#\\"}"
JAVA_HOME="\${JAVA_HOME%\'}"
JAVA_HOME="\${JAVA_HOME#\'}"

if [ "\$RUNTIME_MODE" != "bundled" ]; then
    show_error "Phoenix AWR is not configured to use its official bundled runtime.

Please reinstall Phoenix AWR."
    exit 1
fi

if [ -z "\$JAVA_HOME" ]; then
    show_error "The official Phoenix AWR runtime path is empty.

Please reinstall Phoenix AWR."
    exit 1
fi

JAVA_BIN="\$JAVA_HOME/bin/java"

if [ ! -x "\$JAVA_BIN" ]; then
    show_error "The official Phoenix AWR runtime is missing or damaged.

Expected runtime:
\$JAVA_HOME

Please reinstall Phoenix AWR."
    exit 1
fi

if [ ! -f "\$PHOENIX_JAR" ]; then
    show_error "Phoenix AWR could not be found.

Expected application:
\$PHOENIX_JAR

Please reinstall Phoenix AWR."
    exit 1
fi

PHOENIX_ARGUMENT="\${1:-}"

if [ -z "\$PHOENIX_ARGUMENT" ]; then
    log "Starting Phoenix AWR."

    exec "\$JAVA_BIN" \
        -jar "\$PHOENIX_JAR"
fi

case "\$PHOENIX_ARGUMENT" in
    phoenixawr:*)
        log "Phoenix AWR protocol request received."
        ;;

    http://*|https://*|file://*)
        log "Direct Phoenix AWR target received."
        ;;

    *)
        log "Phoenix AWR application argument received."
        ;;
esac

exec "\$JAVA_BIN" \
    -jar "\$PHOENIX_JAR" \
    "\$PHOENIX_ARGUMENT"
EOF

chmod 755 "$LAUNCHER"

log "[INFO] Phoenix AWR launcher created:"
log "[INFO] $LAUNCHER"

# ============================================================
# Creación del archivo .desktop
# ============================================================

log "[INFO] Creating the Phoenix AWR desktop entry..."

ESCAPED_LAUNCHER="$(escape_desktop_exec_path "$LAUNCHER")"

cat > "$DESKTOP_FILE" <<EOF
[Desktop Entry]
Version=1.0
Type=Application
Name=Phoenix AWR
GenericName=Java Application Compatibility Runtime
Comment=Run Java Applets, JApplets, Web Start and desktop Java applications
Exec="$ESCAPED_LAUNCHER" %u
TryExec=$LAUNCHER
Icon=phoenixawr
Terminal=false
NoDisplay=false
StartupNotify=true
StartupWMClass=Phoenix AWR
MimeType=$URI_MIME;
Categories=Development;Utility;
Keywords=Phoenix;Java;Applet;JApplet;WebStart;JNLP;Swing;JavaFX;
X-GNOME-UsesNotifications=true
EOF

chmod 644 "$DESKTOP_FILE"

if command_exists desktop-file-validate; then
    desktop-file-validate "$DESKTOP_FILE" ||
        fail "The Phoenix AWR desktop entry is invalid."
fi

if command_exists update-desktop-database; then
    update-desktop-database \
        "$APPLICATIONS_DIR" \
        >/dev/null 2>&1 || true
fi

# ============================================================
# Registro de phoenixawr:
# ============================================================

log "[INFO] Registering the phoenixawr protocol..."

xdg-mime default \
    "$DESKTOP_FILENAME" \
    "$URI_MIME"

if command_exists xdg-settings; then
    xdg-settings set \
        default-url-scheme-handler \
        "$URI_SCHEME" \
        "$DESKTOP_FILENAME" \
        >/dev/null 2>&1 || true
fi

REGISTERED_HANDLER="$(
    xdg-mime query default "$URI_MIME" 2>/dev/null || true
)"

if [ "$REGISTERED_HANDLER" != "$DESKTOP_FILENAME" ]; then
    fail "The phoenixawr protocol could not be registered."
fi

log "[INFO] Protocol registered successfully:"
log "[INFO] $URI_MIME -> $REGISTERED_HANDLER"

# ============================================================
# Acceso directo en el escritorio
# ============================================================

log "[INFO] Creating the Phoenix AWR desktop shortcut..."

DESKTOP_SHORTCUT="$DESKTOP_DIR/Phoenix AWR.desktop"

cp -f \
    "$DESKTOP_FILE" \
    "$DESKTOP_SHORTCUT"

chmod 755 "$DESKTOP_SHORTCUT"

if command_exists gio; then
    gio set \
        "$DESKTOP_SHORTCUT" \
        metadata::trusted \
        true \
        >/dev/null 2>&1 || true
fi

log "[INFO] Desktop shortcut created:"
log "[INFO] $DESKTOP_SHORTCUT"

# ============================================================
# Actualización de cachés
# ============================================================

if command_exists update-desktop-database; then
    update-desktop-database \
        "$APPLICATIONS_DIR" \
        >/dev/null 2>&1 || true
fi

if command_exists xdg-desktop-menu; then
    xdg-desktop-menu forceupdate \
        >/dev/null 2>&1 || true
fi

if command_exists gtk-update-icon-cache; then
    gtk-update-icon-cache \
        --force \
        --ignore-theme-index \
        "$ICONS_BASE_DIR" \
        >/dev/null 2>&1 || true
fi

# ============================================================
# Resultado
# ============================================================

echo
echo "============================================================"
echo " Phoenix AWR installed successfully"
echo "============================================================"
echo
echo "Phoenix AWR application:"
echo "  $PHOENIX_JAR"
echo
echo "Phoenix AWR launcher:"
echo "  $LAUNCHER"
echo
echo "Official MC3D runtime:"
echo "  $BUNDLED_JAVA_HOME"
echo
echo "JavaFX validation:"
echo "  OK"
echo
echo "Operating system JVM:"
echo "  Ignored"
echo
echo "Runtime configuration:"
echo "  $JVM_CONF"
echo
echo "Protocol:"
echo "  $URI_SCHEME:"
echo
echo "Protocol handler:"
echo "  $REGISTERED_HANDLER"
echo
echo "Desktop entry:"
echo "  $DESKTOP_FILE"
echo
echo "Desktop shortcut:"
echo "  $DESKTOP_SHORTCUT"
echo
echo "Launch Phoenix AWR:"
echo "  \"$LAUNCHER\""
echo
echo "Test the protocol:"
echo "  xdg-open '${URI_SCHEME}:https://www.mc3d.cl/'"
echo

log "[INFO] Phoenix AWR installation completed successfully."

# ============================================================
# Iniciar Phoenix AWR
# ============================================================

nohup "$LAUNCHER" \
    >> "$STARTUP_LOG" \
    2>&1 &

exit 0
