#!/bin/sh

set -eu

export DEBIAN_FRONTEND=noninteractive

security_package=parrot-menu-security

security_menus="
/etc/xdg/menus/applications-merged/parrot-applications.menu
/etc/xdg/menus/applications-merged/privacy.menu
/etc/xdg/menus/applications-merged/services.menu
"

common_launchers="
/usr/share/applications/parrot-root-terminal.desktop
/usr/share/parrot-menu/applications/parrot-root-terminal.desktop
"

security_launchers="
/usr/share/applications/parrot-nmap.desktop
/usr/share/parrot-menu/applications/parrot-nmap.desktop
"

fail() {
    echo "ERROR: $*" >&2
    exit 1
}

assert_installed() {
    dpkg-query -W -f='${db:Status-Abbrev}' "$1" 2>/dev/null | grep -q '^ii ' ||
        fail "$1 is not installed"
}

assert_not_installed() {
    if dpkg-query -W -f='${db:Status-Abbrev}' "$1" 2>/dev/null | grep -q '^ii '; then
        fail "$1 should not be installed"
    fi
}

assert_file_present() {
    [ -f "$1" ] || fail "$1 is missing"
}

assert_path_absent() {
    [ ! -e "$1" ] || fail "$1 should not exist"
}

assert_home_categories() {
    if grep -RE '^Categories=([^;]+;)*(top10|privacy|cryptography|[0-9][0-9]-)' \
        /usr/share/parrot-menu/applications/*.desktop; then
        fail "common launchers should use standard desktop categories"
    fi
}

assert_home_state() {
    assert_installed parrot-menu
    assert_not_installed "$security_package"

    for path in $common_launchers; do
        assert_file_present "$path"
    done

    assert_home_categories

    for path in $security_menus $security_launchers; do
        assert_path_absent "$path"
    done
}

assert_security_state() {
    assert_installed parrot-menu
    assert_installed "$security_package"

    for path in $common_launchers $security_menus $security_launchers; do
        assert_file_present "$path"
    done
}

if dpkg-query -W "$security_package" >/dev/null 2>&1; then
    apt-get purge -y "$security_package"
fi

assert_home_state

apt-get install -y "$security_package"
assert_security_state

apt-get purge -y "$security_package"
assert_home_state
