# Standalone EasySDR Arch install scriptlet. Ported from easysdr/debian/{postinst,prerm,postrm} (the same
# scripts easysdr/build_deb.py ships), the way packaging/build_rpm.py ports them. This is the plain
# easysdr case: the EasySpotter-only sharing-off step and RTL-SDR udev re-trigger are not included here
# (in Debian they are guarded by the package name / added only by the easyspotter build).

post_install() {
    getent group easysdr >/dev/null || groupadd -r easysdr
    getent passwd easysdr >/dev/null || useradd -r -g easysdr -d /var/lib/easysdr -M -s /usr/bin/nologin -c "EasySDR web SDR" easysdr
    mkdir -p /etc/easysdr
    if [ ! -s /etc/easysdr/owner ]; then
        owner=${SUDO_USER:-}
        if [ -z "$owner" ] && [ -n "${PKEXEC_UID:-}" ]; then owner=$(getent passwd "$PKEXEC_UID" | cut -d: -f1); fi
        if [ -z "$owner" ] && command -v loginctl >/dev/null; then owner=$(loginctl list-sessions --no-legend 2>/dev/null | awk '$4 == "seat0" { print $3; exit }'); fi
        if [ -n "$owner" ] && [ "$owner" != root ]; then echo "$owner" > /etc/easysdr/owner; fi
    fi
    if [ -d /run/systemd/system ]; then
        systemctl daemon-reload || true
        systemctl enable easysdr.service >/dev/null 2>&1 || true
        systemctl restart easysdr.service || true
    fi
    if [ ! -s /etc/easysdr/owner ]; then
        echo "EasySDR: no station owner set. Put your user name in /etc/easysdr/owner, then: systemctl restart easysdr" >&2
    fi
}

post_upgrade() {
    post_install
}

pre_remove() {
    if [ -d /run/systemd/system ]; then
        systemctl disable --now easysdr.service >/dev/null 2>&1 || true
    fi
}

post_remove() {
    # Arch has no "purge": /etc/easysdr and /var/lib/easysdr stay for a reinstall (remove them by hand).
    if [ -d /run/systemd/system ]; then systemctl daemon-reload >/dev/null 2>&1 || true; fi
}
