#!/usr/bin/sh

DKMS=`which dkms 2>/dev/null`
if [ -n "$DKMS" ]
then
    if [ "$1" = "uninstall" ]; then

        echo "Uninstalling modules from DKMS"
        for m in smartcam
        do
            $DKMS status -m $m | while read line
            # first, remove _any_ old module
            do
                if echo "$line" | grep -q added > /dev/null ||
                   echo "$line" | grep -q built > /dev/null ||
                   echo "$line" | grep -q installed > /dev/null; then
                    version=`echo "$line" | sed "s/$m,\([^,]*\)[,:].*/\1/;t;d"`
                    echo "  removing old DKMS module $m version $version"
                    $DKMS remove -m $m -v $version --all
                fi
            done
        done
        # there should not be any more matches
        status=`$DKMS status -m smartcam -v 1.4.0`
        if echo $status | grep added > /dev/null ||
            echo $status | grep built > /dev/null ||
            echo $status | grep installed > /dev/null
        then
            $DKMS remove -m smartcam -v 1.4.0 --all
        fi
        exit 0

    elif [ "$1" = "install" ]; then

        echo "Attempting to install using DKMS"
        if $DKMS add -m smartcam -v 1.4.0 &&
            $DKMS build -m smartcam -v 1.4.0 &&
            $DKMS install -m smartcam -v 1.4.0 --force
        then
            exit 0
        fi
        echo "Failed to install using DKMS, attempting to install without"

    fi
fi

exit 1
