#!/usr/bin/sh

set -e
set -u

BOOT=$(/usr/bin/grep '/boot' '/etc/fstab' | /usr/bin/mawk '$1 !~ /^#/ && $2 ~ /^[/]/ {print $2}')
/usr/bin/test -n "${BOOT}"

if [ -d '/run/systemd/system' ]; then
  /usr/bin/systemctl --system daemon-reload > '/dev/null' 2>&1 || \
    /usr/bin/true
fi

case "${1}" in
  remove|purge)
    if [ -x '/usr/bin/deb-systemd-helper' ]; then
      /usr/bin/deb-systemd-helper purge 'geekworm-naspi-pwmd.service' > '/dev/null' 2>&1 || \
        /usr/bin/true
      /usr/bin/deb-systemd-helper unmask 'geekworm-naspi-pwmd.service' > '/dev/null' 2>&1 || \
        /usr/bin/true
      /usr/bin/deb-systemd-helper purge 'geekworm-naspi-button.service' > '/dev/null' 2>&1 || \
        /usr/bin/true
      /usr/bin/deb-systemd-helper unmask 'geekworm-naspi-button.service' > '/dev/null' 2>&1 || \
        /usr/bin/true
    fi
    /usr/bin/sed --in-place --expression='/^\s*$/N; /## pwm-2chan/,/dtoverlay=pwm-2chan/d' "${BOOT}/config.txt"
    /usr/bin/echo ''
    /usr/bin/echo '################################################'
    /usr/bin/echo '#                                              #'
    /usr/bin/echo '# ! Restart the device to unload the drivers ! #'
    /usr/bin/echo '#                                              #'
    /usr/bin/echo '################################################'
    /usr/bin/echo ''
  ;;
esac
