#!/usr/bin/bash

# Root level functions requiring password for mx-samba-config

# Disable/enable on both systemd and sysV
# Need to run both update-rc.d and systemctl on MX because we have two init systems
SMB=smbd
NMB=nmbd
if [ -f /usr/lib/systemd/system/smb.service ];then
SMB=smb
fi

if [ -f /usr/lib/systemd/system/nmb.service ];then
NMB=nmb
fi

enablesamba()
{
    systemctl unmask $SMB
    systemctl unmask $NMB
    systemctl enable $SMB
    systemctl enable $NMB
}

disablesamba()
{
    systemctl disable $SMB
    systemctl disable $NMB
    systemctl mask $SMB
    systemctl mask $NMB
}

addsambauser()
{
echo -ne "$pass\n$pass" | smbpasswd -as "$user"
exit $?
}

removesambauser()
{
pdbedit --delete "$user"
exit $?
}

changesambapasswd()
{
echo -ne "$pass\n$pass" | smbpasswd -U "$user"
exit $?
}

# service works for starting and stopping on both sysV and systemd
startsamba()
{
    MASKED=$(systemctl is-enabled $SMB)
    systemctl unmask $SMB
    systemctl unmask $NMB
    systemctl start $SMB
    systemctl start $NMB

if [[ -x /usr/bin/systemctl && $MASKED == "masked" ]]; then
    systemctl mask $SMB
    systemctl mask $NMB
fi

exit $?
}

stopsamba()
{
    systemctl stop $SMB
    systemctl stop $NMB

exit $?
}

main()
{
case $1 in
    startsamba)  startsamba
                 ;;
    stopsamba)  stopsamba
                 ;;
    enablesamba)  enablesamba
                 ;;
    disablesamba)  disablesamba
                 ;;
    addsambauser)  user="$3"
                   pass="$2"
                   addsambauser
                   ;;
    removesambauser)  user="$2"
                      removesambauser
                   ;;
    changesambapasswd)  user="$3"
                   pass="$2"
                   changesambapasswd
                   ;;
esac
}

main "$@"
