#!/bin/bash
# postinst: truenas-proxmox-multipath install/upgrade script
set -e

INSTALL_DIR="/usr/share/truenas-proxmox-multipath"
PLUGIN_DST="/usr/share/perl5/PVE/Storage/Custom/TrueNASMultipath.pm"
JS_DST="/usr/share/pve-manager/js/truenas-multipath.js"
TPL="/usr/share/pve-manager/index.html.tpl"
SCRIPT_TAG='    <script type="text/javascript" src="/pve2/js/truenas-multipath.js?ver=[% version %]"></script>'
MULTIPATH_CONF="/etc/multipath.conf"
LOG_FILE="/var/log/truenas-proxmox-install.log"

log() {
    echo "[truenas-proxmox-multipath] $*" | tee -a "$LOG_FILE"
}

install_plugin() {
    log "Installing ${PLUGIN_DST}"
    mkdir -p "$(dirname "$PLUGIN_DST")"
    cp "${INSTALL_DIR}/TrueNASMultipath.pm" "$PLUGIN_DST"
}

install_ui() {
    log "Installing ${JS_DST}"
    cp "${INSTALL_DIR}/truenas-multipath.js" "$JS_DST"

    if grep -qF 'truenas-multipath.js' "$TPL" 2>/dev/null; then
        log "index.html.tpl already has truenas-multipath.js — skipping"
        return 0
    fi

    log "Adding <script> tag to ${TPL}"
    sed -i "/pvemanagerlib\.js/a\\${SCRIPT_TAG}" "$TPL"
}

BLOCK_BEGIN="# BEGIN truenas-proxmox-multipath"
BLOCK_END="# END truenas-proxmox-multipath"

# Appends or replaces the tagged TrueNAS device stanza in multipath.conf.
# Safe to call on upgrade — idempotent via BEGIN/END markers.
install_multipath_conf() {
    local stanza
    stanza=$(cat <<STANZA
${BLOCK_BEGIN}
# Managed by truenas-proxmox-multipath. Do not edit between these markers.
# To customise, remove the package tags and maintain the block yourself.
devices {
    device {
        vendor                "TrueNAS"
        product               "iSCSI Disk"
        path_grouping_policy  multibus
        path_checker          tur
        failback              immediate
        rr_weight             uniform
        no_path_retry         5
    }
}
${BLOCK_END}
STANZA
)

    if [ ! -f "$MULTIPATH_CONF" ]; then
        log "Creating ${MULTIPATH_CONF} with defaults + TrueNAS device stanza"
        printf 'defaults {\n    find_multipaths  yes\n}\n\n%s\n' "$stanza" > "$MULTIPATH_CONF"
    elif grep -qF "$BLOCK_BEGIN" "$MULTIPATH_CONF"; then
        log "Updating existing TrueNAS stanza in ${MULTIPATH_CONF}"
        # Replace the block between markers (inclusive) with the new stanza
        perl -i -0777 -pe \
            "s|\Q${BLOCK_BEGIN}\E.*?\Q${BLOCK_END}\E|${stanza}|s" \
            "$MULTIPATH_CONF"
    else
        log "Appending TrueNAS device stanza to existing ${MULTIPATH_CONF}"
        # Strip any pre-existing unmanaged devices block to prevent duplicate
        # keyword warnings in multipathd (e.g. user had a manual block before install).
        if grep -qE '^\s*devices\s*\{' "$MULTIPATH_CONF"; then
            log "Removing pre-existing unmanaged devices block from ${MULTIPATH_CONF}"
            perl -i -0777 -pe \
                's/\n*\ndevices\s*\{(?:[^{}]*|\{[^{}]*\})*\}\n*//gs' \
                "$MULTIPATH_CONF"
        fi
        printf '\n%s\n' "$stanza" >> "$MULTIPATH_CONF"
    fi

    systemctl enable multipathd 2>/dev/null || true
    systemctl start  multipathd 2>/dev/null || true
    log "multipathd enabled and started"
}

restart_pve_services() {
    log "Restarting Proxmox VE services ..."
    pvedaemon restart && log "pvedaemon restarted"
    pveproxy restart  && log "pveproxy restarted"
    log "Done. Refresh your Proxmox browser tab."
}

case "$1" in
    configure)
        log "Configuring truenas-proxmox-multipath (previous version: ${2:-none})"
        install_plugin
        install_ui
        install_multipath_conf
        restart_pve_services
        ;;
    abort-upgrade|abort-remove|abort-deconfigure)
        ;;
    *)
        echo "$0: called with unknown argument '$1'" >&2
        exit 0
        ;;
esac

exit 0
