#!/bin/bash
# postrm: truenas-proxmox-multipath remove/purge script
set -e

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"
MULTIPATH_CONF="/etc/multipath.conf"
BLOCK_BEGIN="# BEGIN truenas-proxmox-multipath"
BLOCK_END="# END truenas-proxmox-multipath"
LOG_FILE="/var/log/truenas-proxmox-install.log"

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

restart_pve_services() {
    # Bare statements (not `cmd && log ...`) so `set -e` actually aborts on
    # failure instead of silently skipping past it — see tests/test-restart-services.sh.
    log "Restarting Proxmox VE services ..."
    pvedaemon restart
    log "pvedaemon restarted"
    pveproxy restart
    log "pveproxy restarted"
    pvestatd restart
    log "pvestatd restarted"
    systemctl restart pve-ha-lrm pve-ha-crm
    log "pve-ha-lrm, pve-ha-crm restarted"
}

# Guard so tests can `source` this file (to exercise its functions) without
# running dpkg's maintainer-script logic below.
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    case "$1" in
        remove|purge)
            if [ -f "$PLUGIN_DST" ]; then
                log "Removing ${PLUGIN_DST}"
                rm -f "$PLUGIN_DST"
            fi

            if [ -f "$JS_DST" ]; then
                log "Removing ${JS_DST}"
                rm -f "$JS_DST"
            fi

            if [ -f "$TPL" ] && grep -qF 'truenas-multipath.js' "$TPL" 2>/dev/null; then
                log "Removing <script> tag from ${TPL}"
                sed -i '/truenas-multipath\.js/d' "$TPL"
            fi

            if [ -f "$MULTIPATH_CONF" ] && grep -qF "$BLOCK_BEGIN" "$MULTIPATH_CONF"; then
                log "Removing TrueNAS stanza from ${MULTIPATH_CONF}"
                perl -i -0777 -pe \
                    "s|\n?\Q${BLOCK_BEGIN}\E.*?\Q${BLOCK_END}\E\n?||s" \
                    "$MULTIPATH_CONF"
            fi

            restart_pve_services
            log "Done."
            ;;
        upgrade|failed-upgrade|abort-install|abort-upgrade|disappear)
            ;;
        *)
            echo "$0: called with unknown argument '$1'" >&2
            exit 0
            ;;
    esac

    exit 0
fi
