#!/usr/bin/env bash
# gniza4cp installer — from a local clone:
#   bash scripts/install.sh

set -eo pipefail

INSTALL_DIR="/usr/local/gniza4cp"
BIN_LINK="/usr/local/bin/gniza4cp"
REPO_URL="https://git.linux-hosting.co.il/shukivaknin/gniza4cp.git"
TMPDIR_CLONE=""

if [[ $EUID -ne 0 ]]; then
    echo "Error: install.sh must be run as root" >&2
    exit 1
fi

# Determine source directory — local clone or fresh git clone
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-}")" 2>/dev/null && pwd)" || true
if [[ -n "${SCRIPT_DIR:-}" && -f "$SCRIPT_DIR/../bin/gniza4cp" ]]; then
    SOURCE_DIR="$(dirname "$SCRIPT_DIR")"
else
    echo "Cloning gniza4cp..."
    TMPDIR_CLONE="$(mktemp -d)"
    git clone --depth 1 "$REPO_URL" "$TMPDIR_CLONE" 2>&1
    SOURCE_DIR="$TMPDIR_CLONE"
fi

cleanup() { [[ -n "${TMPDIR_CLONE:-}" ]] && rm -rf "$TMPDIR_CLONE"; }
trap cleanup EXIT

echo "Installing gniza4cp to $INSTALL_DIR..."

# Create install directory
mkdir -p "$INSTALL_DIR"

# Copy files
cp -r "$SOURCE_DIR/bin" "$INSTALL_DIR/"
cp -r "$SOURCE_DIR/lib" "$INSTALL_DIR/"
cp -r "$SOURCE_DIR/etc" "$INSTALL_DIR/"
cp "$SOURCE_DIR/scripts/uninstall.sh" "$INSTALL_DIR/uninstall.sh"
chmod +x "$INSTALL_DIR/uninstall.sh"

# Make bin executable
chmod +x "$INSTALL_DIR/bin/gniza4cp"

# Create symlink
ln -sf "$INSTALL_DIR/bin/gniza4cp" "$BIN_LINK"

# Create working directory
mkdir -p "$INSTALL_DIR/workdir"

# Create config directory structure with restrictive permissions
mkdir -p -m 700 /etc/gniza4cp/remotes.d /etc/gniza4cp/schedules.d
chmod 700 /etc/gniza4cp

# Copy example configs if no config exists
if [[ ! -f /etc/gniza4cp/gniza4cp.conf ]]; then
    cp "$INSTALL_DIR/etc/gniza4cp.conf.example" /etc/gniza4cp/gniza4cp.conf.example
    echo "Example config copied to /etc/gniza4cp/gniza4cp.conf.example"
fi
cp "$INSTALL_DIR/etc/remote.conf.example" /etc/gniza4cp/remote.conf.example
cp "$INSTALL_DIR/etc/schedule.conf.example" /etc/gniza4cp/schedule.conf.example

# Create log directory
mkdir -p /var/log/gniza4cp

echo "gniza4cp installed successfully!"

# ── WHM Plugin (if cPanel/WHM is present) ─────────────────────
WHM_CGI_DIR="/usr/local/cpanel/whostmgr/docroot/cgi"
if [[ -d "$WHM_CGI_DIR" ]]; then
    echo "Installing WHM plugin..."
    # Remove old assets cruft (node_modules, src) if upgrading
    rm -rf "$WHM_CGI_DIR/gniza4cp-whm/assets/node_modules" \
           "$WHM_CGI_DIR/gniza4cp-whm/assets/src" \
           "$WHM_CGI_DIR/gniza4cp-whm/assets/package.json" \
           "$WHM_CGI_DIR/gniza4cp-whm/assets/package-lock.json" 2>/dev/null || true
    cp -r "$SOURCE_DIR/whm/gniza4cp-whm" "$WHM_CGI_DIR/"
    cp "$SOURCE_DIR/whm/gniza4cp-whm.conf" "$WHM_CGI_DIR/gniza4cp-whm/"
    chmod +x "$WHM_CGI_DIR/gniza4cp-whm/"*.cgi
    # Remove build artifacts that shouldn't be on the server
    rm -rf "$WHM_CGI_DIR/gniza4cp-whm/assets/node_modules" \
           "$WHM_CGI_DIR/gniza4cp-whm/assets/src" \
           "$WHM_CGI_DIR/gniza4cp-whm/assets/package.json" \
           "$WHM_CGI_DIR/gniza4cp-whm/assets/package-lock.json" 2>/dev/null || true
    /usr/local/cpanel/bin/register_appconfig "$WHM_CGI_DIR/gniza4cp-whm/gniza4cp-whm.conf"
    echo "WHM plugin installed — access via WHM > Plugins > gniza4cp Backup Manager"
else
    echo "WHM not detected, skipping WHM plugin installation."
fi

# ── cPanel User Plugin (if cPanel is present) ────────────────
CPANEL_BASE="/usr/local/cpanel/base/frontend/jupiter"
ADMINBIN_DIR="/usr/local/cpanel/bin/admin/Gniza4cp"
if [[ -d "$CPANEL_BASE" ]]; then
    echo "Installing cPanel user plugin..."
    # Copy CGI files + lib + assets
    mkdir -p "$CPANEL_BASE/gniza4cp/lib/Gniza4cpCPanel" "$CPANEL_BASE/gniza4cp/assets"
    cp "$SOURCE_DIR/cpanel/gniza4cp/index.live.cgi"   "$CPANEL_BASE/gniza4cp/"
    cp "$SOURCE_DIR/cpanel/gniza4cp/restore.live.cgi"  "$CPANEL_BASE/gniza4cp/"
    cp "$SOURCE_DIR/cpanel/gniza4cp/logs.live.cgi"     "$CPANEL_BASE/gniza4cp/"
    chmod +x "$CPANEL_BASE/gniza4cp/"*.cgi
    cp "$SOURCE_DIR/cpanel/gniza4cp/lib/Gniza4cpCPanel/UI.pm" "$CPANEL_BASE/gniza4cp/lib/Gniza4cpCPanel/"
    cp "$SOURCE_DIR/cpanel/gniza4cp/assets/gniza4cp-whm.css"  "$CPANEL_BASE/gniza4cp/assets/"
    cp "$SOURCE_DIR/cpanel/gniza4cp/assets/gniza4cp-logo.svg"  "$CPANEL_BASE/gniza4cp/assets/"
    cp "$SOURCE_DIR/cpanel/gniza4cp/assets/gniza4cp-cpanel-icon.png" "$CPANEL_BASE/gniza4cp/assets/"
    cp "$SOURCE_DIR/cpanel/gniza4cp/install.json"           "$CPANEL_BASE/gniza4cp/"
    # Install AdminBin module (runs as root)
    mkdir -p "$ADMINBIN_DIR"
    cp "$SOURCE_DIR/cpanel/admin/Gniza4cp/Restore"      "$ADMINBIN_DIR/"
    cp "$SOURCE_DIR/cpanel/admin/Gniza4cp/Restore.conf"  "$ADMINBIN_DIR/"
    chmod 0700 "$ADMINBIN_DIR/Restore"
    chmod 0600 "$ADMINBIN_DIR/Restore.conf"
    # Register plugin in cPanel interface (install_plugin expects a tar.gz archive
    # containing install.json + the icon file referenced in it)
    PLUGIN_TMPDIR="$(mktemp -d)"
    mkdir -p "$PLUGIN_TMPDIR/gniza4cp/assets"
    cp "$SOURCE_DIR/cpanel/gniza4cp/install.json" "$PLUGIN_TMPDIR/"
    cp "$SOURCE_DIR/cpanel/gniza4cp/assets/gniza4cp-cpanel-icon.png" "$PLUGIN_TMPDIR/gniza4cp/assets/"
    tar -czf "$PLUGIN_TMPDIR/gniza4cp-cpanel.tar.gz" -C "$PLUGIN_TMPDIR" install.json gniza4cp/assets/gniza4cp-cpanel-icon.png
    /usr/local/cpanel/scripts/install_plugin "$PLUGIN_TMPDIR/gniza4cp-cpanel.tar.gz" 2>/dev/null || true
    rm -rf "$PLUGIN_TMPDIR"
    # Rebuild icon sprites so the new icon appears in cPanel
    /usr/local/cpanel/bin/rebuild_sprites 2>/dev/null || true
    # Regenerate per-user sprites for all cPanel accounts
    if [[ -f /etc/trueuserdomains ]]; then
        while IFS=: read -r _ user; do
            user="${user// /}"
            [[ -n "$user" ]] && cpapi2 --user="$user" Branding gensprites 2>/dev/null || true
        done < /etc/trueuserdomains
    fi
    echo "cPanel user plugin installed — users will see gniza4cp Restore in Files section"
else
    echo "cPanel not detected, skipping cPanel user plugin installation."
fi

echo ""
echo "Next steps:"
echo "  Open WHM → GNIZA4CP Backup Manager to configure via the setup wizard."
