#!/bin/sh
# install-neoflux-bin.sh — install or remove a NeoFlux binary tarball made by
# make-bin-tarball.sh. Run IN A ROOT SHELL:
#
#   sh install-neoflux-bin.sh /var/tmp/neoflux-bin-<version>-<arch>.tar.gz
#   sh install-neoflux-bin.sh --uninstall
#
# Install extracts the archive over / (files land in /usr/local plus the one
# xsessions entry) and never touches anything portage owns. Uninstall removes
# exactly the files listed in the package's manifest, then prunes any
# directories that became empty.
set -eu

MANIFEST=/usr/local/share/doc/neoflux-bin/manifest.txt

if [ "$(id -u)" != 0 ]; then
    echo "install-neoflux-bin.sh: run this in a root shell" >&2
    exit 1
fi

if [ "${1:-}" = "--uninstall" ]; then
    if [ ! -r "$MANIFEST" ]; then
        echo "no manifest at $MANIFEST — nothing to uninstall" >&2
        exit 1
    fi
    echo "removing files listed in $MANIFEST:"
    while IFS= read -r f; do
        # Only ever remove from the two prefixes this package installs to.
        case "$f" in
            /usr/local/*|/usr/share/xsessions/neoflux-bin.desktop|/usr/share/xsessions/nfmc-bin.desktop)
                rm -fv "$f" ;;
            *)
                echo "  skipping unexpected manifest entry: $f" >&2 ;;
        esac
    done < "$MANIFEST"
    rmdir -p /usr/local/share/doc/neoflux-bin 2>/dev/null || true
    echo "done."
    exit 0
fi

TARBALL=${1:-}
if [ -z "$TARBALL" ] || [ ! -r "$TARBALL" ]; then
    echo "usage: sh install-neoflux-bin.sh <neoflux-bin-....tar.gz> | --uninstall" >&2
    exit 1
fi

# Sanity: refuse an archive containing anything outside the expected prefixes.
if tar -tzf "$TARBALL" | grep -Ev '^\./($|usr/$|usr/local/|usr/share/$|usr/share/xsessions/)' ; then
    echo "REFUSING: archive contains paths outside /usr/local and /usr/share/xsessions (listed above)" >&2
    exit 1
fi

echo "installing $TARBALL:"
# --no-same-owner: own extracted files as root, ignoring archive uid/gid.
# --no-overwrite-dir: leave ownership/mode of existing dirs (/usr, /usr/local,
# /usr/share, ...) untouched.
tar -C / --no-same-owner --no-overwrite-dir -xvpzf "$TARBALL"
echo
echo "installed. Log out and pick the 'NeoFlux (bin)' session in SDDM."
echo "(man pages: man neoflux — /usr/local/share/man is on the default manpath)"
