#!/usr/bin/env bash

. /usr/share/dosis2/bin/shell-support-functions

enforce_root

OPTION=""
CUPS_SERVICE_D="/etc/systemd/system/cups.service.d/"
CUPS_OVERRIDE="${CUPS_SERVICE_D}override.conf"

echo_help() {
echo "set-cups-sssd-compatibility [-h] [-e] [-d] 
-h | --help       show help
-e | --enable     set option to start cups after sssd 
-d | --disable    set revert back to original state
"
}

if [ "$1" = "" ]; then
    echo "No option selected"
    echo_help
    exit 1
else
    case $1 in 
        -e | --enable )     shift
                            OPTION="e"
                            ;;
        -d | --disable )    shift
                            OPTION="d"
                            ;;
        -h | --help )       echo_help
                            exit
                            ;;
        * )                 echo_help
                            exit 1
    esac
fi

set_ubuntu() {
    if [ "$OPTION" =  "e" ]; then # create file to start cups after sssd has finished
        if [ -f "${CUPS_OVERRIDE}" ]; then
            echo "override already exists"
            cat "${CUPS_OVERRIDE}"
            echo "done"
        else
            mkdir -p "${CUPS_SERVICE_D}"
            cat <<EOF > "${CUPS_OVERRIDE}"
[Unit]
After=sssd.service
EOF
            echo "done"
        fi
    elif [ "$OPTION" = "d" ]; then # just remove the override file from /etc/systemd/system/cups.service.d
        if [ -f "${CUPS_OVERRIDE}" ]; then
            rm -f "${CUPS_OVERRIDE}"
            echo "done"
        else
            echo "Override doesn't exist nothing to do..."
        fi
    else
        echo "invalid option"
        echo_help
        exit 1
    fi
}

set_ubuntu
