#!/bin/bash

set -euo pipefail

export DEBIAN_FRONTEND=noninteractive
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${PATH:-}"
# In case the parent process closes stdout (like a background update task),
# we redirect all output to a log file to avoid being killed by SIGPIPE.
if [[ ! -t 1 ]]; then
    exec >> /var/log/limristem_update.log 2>&1
    # Ensure the log file is not world-readable (it may contain credentials)
    chmod 600 /var/log/limristem_update.log 2>/dev/null || true
fi

APP_DISPLAY_NAME="Limristem Web"
SOURCE_DIR="limristem_web"
INSTALL_DIR="/opt/limristem-web"
SERVICE_NAME="limristem-web"
PANEL_SITE_NAME="limristem-web-panel"
PROXY_SITE_NAME="limristem-web"
ZONE_FILE="/etc/nginx/conf.d/limristem-web_zones.conf"

if [[ "${EUID}" -ne 0 ]]; then
    echo "Please run as root"
    exit 1
fi

write_secret_config() {
    local path="$1"
    local secret_key="$2"
    python3 - "$path" "$secret_key" <<'PY'
import json
import os
import sys

path, secret_key = sys.argv[1], sys.argv[2]
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as handle:
    json.dump({"SECRET_KEY": secret_key}, handle)
os.chmod(path, 0o600)
PY
}

write_mysql_config() {
    local path="$1"
    local password="$2"
    python3 - "$path" "$password" <<'PY'
import json
import os
import sys

path, password = sys.argv[1], sys.argv[2]
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as handle:
    json.dump({"host": "127.0.0.1", "user": "root", "password": password}, handle)
os.chmod(path, 0o600)
PY
}

update_hosts_entry() {
    local hostname_value="$1"
    # Create a temporary file
    local tmp_hosts
    tmp_hosts=$(mktemp)
    
    awk -v hn="$hostname_value" '
    BEGIN { updated = 0 }
    $1 == "127.0.0.1" {
        # Check if it contains localhost
        has_localhost = 0
        for (i=2; i<=NF; i++) {
            if ($i == "localhost") has_localhost = 1
        }
        if (has_localhost == 0 && updated == 0) {
            # Update the first 127.0.0.1 line that is not localhost
            $2 = hn
            updated = 1
        }
    }
    { print }
    END {
        if (updated == 0) {
            print "127.0.0.1 " hn
        }
    }' /etc/hosts > "$tmp_hosts"
    
    cat "$tmp_hosts" > /etc/hosts
    rm -f "$tmp_hosts"
}

validate_mysql_root_password() {
    local password="$1"
    MYSQL_PWD="$password" mysql -u root -e "SELECT 1" >/dev/null 2>&1
}

HOSTNAME_ARG=""
OVERWRITE_ARG=false
UPDATE_ARG=false
PROXY_ARG=false
PROXY_PATH_ARG=""
MYSQL_ACTION=""
MYSQL_PASS_ARG=""
INTERACTIVE_MODE=true

if [[ $# -gt 0 ]]; then
    INTERACTIVE_MODE=false
fi

while [[ $# -gt 0 ]]; do
    case "$1" in
        -h)
            HOSTNAME_ARG="${2:-}"
            shift 2
            ;;
        -o)
            OVERWRITE_ARG=true
            shift
            ;;
        -U)
            UPDATE_ARG=true
            shift
            ;;
        -p)
            PROXY_ARG=true
            if [[ -n "${2:-}" && "${2:-}" != -* ]]; then
                PROXY_PATH_ARG="$2"
                shift 2
            else
                shift
            fi
            ;;
        -s)
            if [[ -n "${2:-}" && "${2:-}" != -* ]]; then
                MYSQL_ACTION="existing"
                MYSQL_PASS_ARG="$2"
                shift 2
            else
                MYSQL_ACTION="install"
                shift
            fi
            ;;
        *)
            echo "Unknown option $1"
            exit 1
            ;;
    esac
done

if [[ "$OVERWRITE_ARG" == true && "$UPDATE_ARG" == true ]]; then
    echo "Error: -o (overwrite) and -U (update) cannot be used together."
    exit 1
fi

echo "Checking system compatibility..."
if [[ -f /etc/os-release ]]; then
    . /etc/os-release
    if [[ "$ID" != "debian" ]]; then
        echo "Error: this installer supports Debian only."
        exit 1
    fi
    VERSION_ID_NUM="$(echo "$VERSION_ID" | cut -d. -f1)"
    if [[ "$VERSION_ID_NUM" -lt 13 ]]; then
        echo "Error: Debian 13 or higher is required. Found $VERSION_ID."
        exit 1
    fi
    echo "System detected: Debian $VERSION_ID"
else
    echo "Error: cannot detect OS version."
    exit 1
fi

if [[ -n "$HOSTNAME_ARG" ]]; then
    SERVER_HOSTNAME="$HOSTNAME_ARG"
elif [[ "$INTERACTIVE_MODE" == true ]]; then
    read -r -p "Enter the hostname for this server (e.g. srv1.example.com): " SERVER_HOSTNAME
else
    SERVER_HOSTNAME="$(hostname)"
    echo "No hostname argument provided. Using current hostname: $SERVER_HOSTNAME"
fi

if [[ -z "$SERVER_HOSTNAME" ]]; then
    echo "Hostname cannot be empty."
    exit 1
fi

if [[ ! "$SERVER_HOSTNAME" =~ ^[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?$ ]]; then
    echo "Error: Invalid hostname '$SERVER_HOSTNAME'. Only alphanumeric characters, dots, and dashes are allowed."
    exit 1
fi

echo "Setting hostname to $SERVER_HOSTNAME..."
echo "$SERVER_HOSTNAME" > /etc/hostname
hostname "$SERVER_HOSTNAME" || true
update_hosts_entry "$SERVER_HOSTNAME"

INSTALL_PROXY="N"
PROXY_PATH=""
if [[ "$PROXY_ARG" == true ]]; then
    INSTALL_PROXY="y"
    if [[ -n "$PROXY_PATH_ARG" ]]; then
        PROXY_PATH="$PROXY_PATH_ARG"
    else
        PROXY_PATH="/$(openssl rand -hex 4)"
    fi
elif [[ "$INTERACTIVE_MODE" == true ]]; then
    read -r -p "Expose the panel through Nginx proxy on ports 80/443? [y/N]: " INSTALL_PROXY_INPUT
    INSTALL_PROXY="${INSTALL_PROXY_INPUT:-N}"
    if [[ "$INSTALL_PROXY" =~ ^[yY]$ ]]; then
        DEFAULT_PATH="/$(openssl rand -hex 4)"
        read -r -p "Enter the secure proxy path (default: $DEFAULT_PATH): " PROXY_PATH
        PROXY_PATH="${PROXY_PATH:-$DEFAULT_PATH}"
    fi
fi

if [[ -n "$PROXY_PATH" && "$PROXY_PATH" != /* ]]; then
    PROXY_PATH="/$PROXY_PATH"
fi

if [[ -n "$PROXY_PATH" && ! "$PROXY_PATH" =~ ^/[A-Za-z0-9._/-]+$ ]]; then
    echo "Error: Invalid proxy path '$PROXY_PATH'. Only alphanumeric characters, dots, dashes, and slashes are allowed."
    exit 1
fi

INSTALL_MYSQL="N"
MYSQL_ROOT_PASS=""
WIPE_MYSQL=false
if [[ "$MYSQL_ACTION" == "install" ]]; then
    INSTALL_MYSQL="y"
elif [[ "$MYSQL_ACTION" == "existing" ]]; then
    INSTALL_MYSQL="existing"
    MYSQL_ROOT_PASS="$MYSQL_PASS_ARG"
elif [[ "$INTERACTIVE_MODE" == true ]]; then
    read -r -p "Install and configure MySQL/MariaDB server? [y/N]: " INSTALL_MYSQL_INPUT
    INSTALL_MYSQL="${INSTALL_MYSQL_INPUT:-N}"
    if [[ "$INSTALL_MYSQL" =~ ^[yY]$ ]]; then
        if command -v mysql >/dev/null 2>&1 || dpkg -l | grep -E "^ii  (mariadb-server|mysql-server)" >/dev/null 2>&1; then
            while true; do
                read -r -p "MySQL/MariaDB is already installed. Enter root password to verify: " MYSQL_ROOT_PASS_INPUT
                if validate_mysql_root_password "$MYSQL_ROOT_PASS_INPUT"; then
                    echo "Password is correct."
                    INSTALL_MYSQL="existing"
                    MYSQL_ROOT_PASS="$MYSQL_ROOT_PASS_INPUT"
                    break
                else
                    echo "Incorrect password or not root user."
                    while true; do
                        read -r -p "Do you want to (s)kip MySQL setup or (w)ipe and reinstall? [s/W]: " MYSQL_FAIL_CHOICE
                        MYSQL_FAIL_CHOICE="${MYSQL_FAIL_CHOICE:-W}"
                        if [[ "$MYSQL_FAIL_CHOICE" =~ ^[sS]$ ]]; then
                            INSTALL_MYSQL="N"
                            MYSQL_ROOT_PASS=""
                            break 2
                        elif [[ "$MYSQL_FAIL_CHOICE" =~ ^[wW]$ ]]; then
                            WIPE_MYSQL=true
                            break 2
                        fi
                    done
                fi
            done
        fi
    fi
fi

UPDATE_CHOICE="U"
if [[ -d "$INSTALL_DIR" ]]; then
    if [[ "$OVERWRITE_ARG" == true ]]; then
        UPDATE_CHOICE="o"
    elif [[ "$UPDATE_ARG" == true ]]; then
        UPDATE_CHOICE="U"
    elif [[ "$INTERACTIVE_MODE" == true ]]; then
        read -r -p "Limristem Web is already installed. Do you want to [U]pdate (keep data) or [O]verwrite (clean install)? [U/o]: " UPDATE_CHOICE_INPUT
        UPDATE_CHOICE="${UPDATE_CHOICE_INPUT:-U}"
    fi
fi

echo "Updating system packages..."
apt-get update || true
apt-get upgrade -y || true

echo "Installing core dependencies..."
apt-get install -y git curl wget unzip acl mdadm smartmontools sudo build-essential lsb-release ca-certificates apt-transport-https gnupg2 screen || true

echo "Installing Python dependencies..."
apt-get install -y python3 python3-venv python3-pip python3-dev libffi-dev libssl-dev || true

echo "Installing web server dependencies..."
apt-get install -y nginx certbot python3-certbot-nginx || true

mkdir -p /etc/nginx/conf.d
printf 'limit_conn_zone $binary_remote_addr zone=addr:10m;\n' > "$ZONE_FILE"
apt-get install -f -y || true

echo "Setting up the Sury PHP repository..."
PHP_CODENAME="${VERSION_CODENAME:-$(lsb_release -sc)}"
curl -fsSL -o /usr/share/keyrings/deb.sury.org-php.gpg https://packages.sury.org/php/apt.gpg || { echo "Error: Failed to download Sury PHP GPG key."; exit 1; }
echo "deb [signed-by=/usr/share/keyrings/deb.sury.org-php.gpg] https://packages.sury.org/php/ $PHP_CODENAME main" > /etc/apt/sources.list.d/php.list
apt-get update

echo "Installing PHP 8.2 and common extensions..."
apt-get install -y php8.2 php8.2-fpm php8.2-cli php8.2-common php8.2-mysql php8.2-curl php8.2-gd php8.2-mbstring php8.2-xml php8.2-zip php8.2-intl php8.2-bcmath
systemctl enable php8.2-fpm
systemctl start php8.2-fpm

echo "Installing to $INSTALL_DIR..."
DO_UPDATE=0

if [[ -d "$INSTALL_DIR" ]]; then
    echo "$APP_DISPLAY_NAME is already installed."
    if [[ "$OVERWRITE_ARG" == true ]]; then
        UPDATE_CHOICE="o"
    elif [[ "$UPDATE_ARG" == true ]]; then
        UPDATE_CHOICE="U"
    fi
    UPDATE_CHOICE="${UPDATE_CHOICE:-U}"

    if [[ "$UPDATE_CHOICE" =~ ^[oO]$ ]]; then
        backup_dir="$(mktemp -d "${INSTALL_DIR}_backup_XXXXXX")"
        echo "Backing up the current installation to $backup_dir"
        mv "$INSTALL_DIR" "$backup_dir"
    else
        DO_UPDATE=1
        echo "Updating existing installation and preserving data."
    fi
fi

if [[ "$DO_UPDATE" -eq 0 || ! -f "$INSTALL_DIR/instance/config.json" ]]; then
    SECRET_KEY="$(python3 -c 'import secrets; print(secrets.token_hex(32))')"
fi

if [[ ! -d "$SOURCE_DIR" ]]; then
    echo "Error: source directory '$SOURCE_DIR' not found."
    exit 1
fi

if [[ "$DO_UPDATE" -eq 1 ]]; then
    temp_update_dir="$(mktemp -d)"
    if [[ -d "$INSTALL_DIR/instance" ]]; then
        cp -a "$INSTALL_DIR/instance" "$temp_update_dir/"
    fi
    mkdir -p "$INSTALL_DIR"
    cp -af "$SOURCE_DIR/." "$INSTALL_DIR/"
    if [[ -d "$temp_update_dir/instance" ]]; then
        mkdir -p "$INSTALL_DIR/instance"
        cp -af "$temp_update_dir/instance/." "$INSTALL_DIR/instance/"
    fi
    rm -rf "$temp_update_dir"
else
    mkdir -p "$INSTALL_DIR"
    cp -af "$SOURCE_DIR/." "$INSTALL_DIR/"
    rm -f "$INSTALL_DIR/limristem_web.sqlite" "$INSTALL_DIR/instance/limristem_web.sqlite"
    cp -af install.sh "$INSTALL_DIR/install.sh"
    chmod +x "$INSTALL_DIR/install.sh"
fi

echo "Creating virtual environment..."
python3 -m venv "$INSTALL_DIR/venv"
source "$INSTALL_DIR/venv/bin/activate"
pip install --upgrade pip
pip install -r "$INSTALL_DIR/requirements.txt"

mkdir -p "$INSTALL_DIR/instance"
if [[ ! -f "$INSTALL_DIR/instance/config.json" ]]; then
    write_secret_config "$INSTALL_DIR/instance/config.json" "$SECRET_KEY"
fi

if [[ ! -f "$INSTALL_DIR/instance/panel_nginx.conf" ]]; then
    cat > "$INSTALL_DIR/instance/panel_nginx.conf" <<EOF
client_max_body_size 100M;
proxy_read_timeout 300s;
proxy_connect_timeout 300s;
proxy_send_timeout 300s;
EOF
fi

if [[ ! -f "$INSTALL_DIR/instance/panel.key" ]]; then
    echo "Generating primary CA and self-signed certificate for the panel..."
    
    # 1. Generate CA
    openssl req -x509 -nodes -days 3650 -newkey rsa:2048 \
        -keyout "$INSTALL_DIR/instance/primary_ca.key" \
        -out "$INSTALL_DIR/instance/primary_ca.crt" \
        -subj "/C=IT/ST=Italy/L=Rome/O=Limristem Web/OU=CA/CN=Limristem Primary CA" \
        -addext "basicConstraints=critical,CA:TRUE" \
        -addext "keyUsage=critical,keyCertSign,cRLSign" 2>/dev/null
    
    # 2. Generate Panel CSR
    openssl req -new -nodes -newkey rsa:2048 \
        -keyout "$INSTALL_DIR/instance/panel.key" \
        -out "$INSTALL_DIR/instance/panel.csr" \
        -subj "/C=IT/ST=Italy/L=Rome/O=Limristem Web/OU=Panel/CN=$SERVER_HOSTNAME" 2>/dev/null

    # 3. Sign Panel Cert with CA
    echo "subjectAltName=DNS:$SERVER_HOSTNAME" > "$INSTALL_DIR/instance/panel.ext"
    openssl x509 -req -in "$INSTALL_DIR/instance/panel.csr" \
        -CA "$INSTALL_DIR/instance/primary_ca.crt" \
        -CAkey "$INSTALL_DIR/instance/primary_ca.key" \
        -CAcreateserial -out "$INSTALL_DIR/instance/panel.crt" \
        -days 3650 -extfile "$INSTALL_DIR/instance/panel.ext" 2>/dev/null
        
    rm -f "$INSTALL_DIR/instance/panel.csr" "$INSTALL_DIR/instance/panel.ext" "$INSTALL_DIR/instance/primary_ca.srl"
    chmod 600 "$INSTALL_DIR/instance/panel.key" "$INSTALL_DIR/instance/primary_ca.key"
fi

echo "Creating systemd service..."
cat > "/etc/systemd/system/${SERVICE_NAME}.service" <<EOF
[Unit]
Description=${APP_DISPLAY_NAME} web interface
After=network.target

[Service]
User=root
Group=root
WorkingDirectory=${INSTALL_DIR}
Environment="PATH=${INSTALL_DIR}/venv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
ExecStart=${INSTALL_DIR}/venv/bin/gunicorn -w 1 -b 127.0.0.1:4317 --timeout 300 'app:create_app()'
Restart=always
RestartSec=5

# Hardening (tuned for a control panel that manages users, nginx, php, packages)
PrivateTmp=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
ProtectClock=true
ProtectHostname=true
RestrictRealtime=true
LockPersonality=true

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable "$SERVICE_NAME"
systemctl restart "$SERVICE_NAME"

MYSQL_CONFIG_FAILED=0
MYSQL_CONFIG_PATH="$INSTALL_DIR/instance/mysql_config.json"

if [[ "$WIPE_MYSQL" == true ]]; then
    echo "Wiping existing MySQL/MariaDB installation..."
    systemctl stop mysql mariadb >/dev/null 2>&1 || true
    apt-get purge -y mariadb-server mariadb-client mariadb-common mysql-server mysql-client mysql-common || true
    apt-get autoremove -y || true
    rm -rf /etc/mysql /var/lib/mysql
fi

if [[ "$INSTALL_MYSQL" == "existing" && -n "$MYSQL_ROOT_PASS" ]]; then
    write_mysql_config "$MYSQL_CONFIG_PATH" "$MYSQL_ROOT_PASS"
elif [[ "$INSTALL_MYSQL" =~ ^[yY]$ ]]; then
    echo "Installing MariaDB server..."
    apt-get install -y mariadb-server || true
    for _ in {1..30}; do
        if mysql -e "SELECT 1" >/dev/null 2>&1; then
            break
        fi
        sleep 1
    done

    MYSQL_ROOT_PASS="$(openssl rand -base64 48 | tr -dc 'A-Za-z0-9@#%^*_+=?' | head -c 32)"
    MYSQL_PWD="" mysql -e "ALTER USER 'root'@'localhost' IDENTIFIED BY '${MYSQL_ROOT_PASS}';"
    export MYSQL_PWD="$MYSQL_ROOT_PASS"
    mysql -e "DELETE FROM mysql.user WHERE User='';"
    mysql -e "DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');"
    mysql -e "DROP DATABASE IF EXISTS test;"
    mysql -e "DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';"
    mysql -e "FLUSH PRIVILEGES;"
    unset MYSQL_PWD

    if [[ -f /etc/mysql/mariadb.conf.d/50-server.cnf ]]; then
        sed -i 's/^bind-address.*/bind-address = 127.0.0.1/' /etc/mysql/mariadb.conf.d/50-server.cnf
        systemctl restart mariadb
    fi

    write_mysql_config "$MYSQL_CONFIG_PATH" "$MYSQL_ROOT_PASS"
    echo "MariaDB installed and secured."
fi

echo "Configuring panel Nginx block..."
cat > "/etc/nginx/sites-available/${PANEL_SITE_NAME}" <<EOF
server {
    listen 8016;
    server_name _;
    server_tokens off;
    return 301 https://\$host:4316\$request_uri;
}

server {
    listen 4316 ssl;
    server_name _;
    server_tokens off;

    ssl_certificate ${INSTALL_DIR}/instance/panel.crt;
    ssl_certificate_key ${INSTALL_DIR}/instance/panel.key;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1d;
    ssl_session_tickets off;
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;

    include ${INSTALL_DIR}/instance/panel_nginx.conf;

    location / {
        proxy_pass http://127.0.0.1:4317;
        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;
    }
}
EOF
ln -sfn "/etc/nginx/sites-available/${PANEL_SITE_NAME}" "/etc/nginx/sites-enabled/${PANEL_SITE_NAME}"

FINAL_URL="https://${SERVER_HOSTNAME}:4316/"

if [[ "$INSTALL_PROXY" =~ ^[yY]$ ]]; then
    echo "Configuring Nginx proxy snippet..."
    cat > "${INSTALL_DIR}/instance/panel_proxy_location.conf" <<EOF
    location ${PROXY_PATH} {
        include ${INSTALL_DIR}/instance/panel_nginx.conf;
        proxy_pass http://127.0.0.1:4317/;
        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 X-Forwarded-Prefix ${PROXY_PATH};
    }
EOF

    echo "Creating panel proxy vhost on ports 80/443..."
    cat > "/etc/nginx/sites-available/${PROXY_SITE_NAME}" <<EOF
server {
    listen 80;
    server_name ${SERVER_HOSTNAME};
    server_tokens off;
    return 301 https://\$host\$request_uri;
}

server {
    listen 443 ssl;
    server_name ${SERVER_HOSTNAME};
    server_tokens off;

    ssl_certificate ${INSTALL_DIR}/instance/panel.crt;
    ssl_certificate_key ${INSTALL_DIR}/instance/panel.key;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1d;
    ssl_session_tickets off;
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;

    include ${INSTALL_DIR}/instance/panel_proxy_location.conf;

    location / {
        root ${INSTALL_DIR}/static/default_page;
        index index.html;
    }
}
EOF
    ln -sfn "/etc/nginx/sites-available/${PROXY_SITE_NAME}" "/etc/nginx/sites-enabled/${PROXY_SITE_NAME}"
    rm -f /etc/nginx/sites-enabled/default
    FINAL_URL="https://${SERVER_HOSTNAME}${PROXY_PATH}"
fi

nginx -t
systemctl reload nginx

if [[ "$DO_UPDATE" -eq 0 ]]; then
    ADMIN_USER="$(shuf -i 10000000-99999999 -n 1)"
    ADMIN_PASS="$(openssl rand -base64 48 | tr -dc 'a-zA-Z0-9' | head -c 32)"

    echo "Setting up admin credentials..."
    "$INSTALL_DIR/venv/bin/python3" "$INSTALL_DIR/setup_admin.py" \
        "$INSTALL_DIR" "$ADMIN_USER" "$ADMIN_PASS" "$SERVER_HOSTNAME"

    # Secure the installation directory
    chown -R root:root "$INSTALL_DIR"
    chmod 755 "$INSTALL_DIR"
    chmod 700 "$INSTALL_DIR/instance"
    chmod 600 "$INSTALL_DIR/instance/panel.key" 2>/dev/null || true
    if [[ -f "$INSTALL_DIR/instance/limristem_web.sqlite" ]]; then
        chmod 600 "$INSTALL_DIR/instance/limristem_web.sqlite"
    fi

    detected_ip="${PUBLIC_IP:-}"
    if [[ -z "$detected_ip" ]]; then
      detected_ip=$(hostname -I 2>/dev/null | awk '{print $1}') || detected_ip="<server-ip>"
    fi

    echo ""
    echo "============================================================"
    echo " Installazione Limristem Web completata"
    echo "============================================================"
    echo ""
    echo " Hostname  : $SERVER_HOSTNAME"
    echo " Server IP : $detected_ip"
    echo " Log file  : /var/log/limristem_update.log"
    echo ""
    echo "--- Pannello Web ---"
    echo " URL         : ${FINAL_URL}"
    echo " URL (IP)    : ${FINAL_URL/$SERVER_HOSTNAME/$detected_ip}"
    echo " Admin user  : ${ADMIN_USER}"
    echo " Admin pass  : ${ADMIN_PASS}"
    echo ""
    if [[ -n "$MYSQL_ROOT_PASS" ]]; then
        echo " MySQL Root Password: ${MYSQL_ROOT_PASS}"
        echo ""
    fi
    echo "============================================================"
    echo ""
else
    # Secure the installation directory for updates
    chown -R root:root "$INSTALL_DIR"
    chmod 755 "$INSTALL_DIR"
    chmod 700 "$INSTALL_DIR/instance"
    chmod 600 "$INSTALL_DIR/instance/panel.key" 2>/dev/null || true
    if [[ -f "$INSTALL_DIR/instance/limristem_web.sqlite" ]]; then
        chmod 600 "$INSTALL_DIR/instance/limristem_web.sqlite"
    fi
    echo "Update complete. Existing credentials remain valid."
fi

if [[ "$MYSQL_CONFIG_FAILED" -eq 1 ]]; then
    echo ""
    echo "WARNING: MySQL configuration failed."
    echo "The CLI password provided for the existing MySQL root account was incorrect."
    echo "MySQL features will remain unavailable until ${MYSQL_CONFIG_PATH} is configured correctly."
fi
