#!/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)
    if [ -x '/usr/bin/deb-systemd-helper' ]; then
      /usr/bin/deb-systemd-helper mask 'pironman5.service' > '/dev/null' 2>&1 || \
        /usr/bin/true
      /usr/bin/deb-systemd-helper mask 'pironman5-led.service' > '/dev/null' 2>&1 || \
        /usr/bin/true
    fi
  ;;
  purge)
    if [ -x '/usr/bin/deb-systemd-helper' ]; then
      /usr/bin/deb-systemd-helper purge 'pironman5.service' > '/dev/null' 2>&1 || \
        /usr/bin/true
      /usr/bin/deb-systemd-helper unmask 'pironman5.service' > '/dev/null' 2>&1 || \
        /usr/bin/true
      /usr/bin/deb-systemd-helper purge 'pironman5-err.service' > '/dev/null' 2>&1 || \
        /usr/bin/true
      /usr/bin/deb-systemd-helper unmask 'pironman5-err.service' > '/dev/null' 2>&1 || \
        /usr/bin/true
    fi
    /usr/bin/rm --force --recursive '/opt/pironman5'
    if ! /usr/bin/grep --quiet 'dtparam=i2c_arm=on' "${BOOT}/config.txt"; then
      /usr/bin/sed --in-place --expression='/dtparam=i2c_arm=on/dtparam=spi=off/' "${BOOT}/config.txt"
    fi
    if ! /usr/bin/grep --quiet 'dtparam=spi=on' "${BOOT}/config.txt"; then
      /usr/bin/sed --in-place --expression='/dtparam=spi=on/dtparam=spi=off/' "${BOOT}/config.txt"
    fi
    /usr/bin/sed --in-place --expression='/^\s*$/N; /## sunfounder-pironman5/,/dtoverlay=sunfounder-pironman5,ir=off/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

/usr/bin/rm --force --recursive '/var/log/gitea'
/usr/bin/rm --force --recursive '/var/logrotate/gitea'
