#!/bin/bash

BASENAME=${0##*/}

case $BASENAME in
    udevadm)
        # This is a workaround for preventing Kodi to crash while installing update(s)
        # Under some conditions Kodi will crash when dpkg scripts are running command
        # udevadm trigger ... (package pulseaudio does this)
        if pgrep dpkg >/dev/null && pgrep "xbmc.bin|kodi.bin" >/dev/null && [ "$1" == trigger ]; then
            echo $BASENAME $@
            echo "$BASENAME $@" >>/var/run/reboot-required
            exit 0
        fi
        exec /bin/$BASENAME $@
        ;;
    invoke-rc.d)
        # This is a workaround for preventing system to crash while installing update(s)
        # Currently when running under Debian Stretch, system crashes mostly when udev
        # package is being updated and a restart of daemon is invoked
        if [ "$1" == udev ] && [ "$2" == restart ]; then
            echo $BASENAME $@
            echo "$BASENAME $@" >>/var/run/reboot-required
            exit 0
        fi
        exec /usr/sbin/$BASENAME $@
        ;;
    update-rc.d)
        # This is a workaround for preventing dist-upgrade to break while
        # open-iscsi is going to be upgraded
        if [ "$1" == iscsid -o "$1" == open-iscsi ] && [ "$2" == defaults-disabled ]; then
            exit 0
        fi
        [ -x /usr/sbin/$BASENAME ] && exec /usr/sbin/$BASENAME $@
        [ -x /usr/bin/$BASENAME ] && exec /usr/bin/$BASENAME $@
        ;;
    mountpoint)
        # This is a workaround for preventing package usrmerge
        # fails installing if /lib/modules is a mountpoint
        # See Debian Bug #1021180
        if [ "$1" == '-q' ] && [ "$2" == '/lib/modules/' ]; then
            umount -l /lib/modules
            ( sleep 60 && mount /lib/modules; ) &
        fi
        exec /bin/$BASENAME $@
        ;;
esac
