#!/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
enablesamba()
{
if [ -x /usr/sbin/update-rc.d ]; then
    update-rc.d smbd remove
    update-rc.d nmbd remove
    update-rc.d smbd defaults
    update-rc.d nmbd defaults
fi
if [ -x /usr/bin/systemctl ]; then
    systemctl unmask smbd
    systemctl unmask nmbd
    systemctl enable smbd
    systemctl enable nmbd
fi
}

disablesamba()
{
if [ -x /usr/sbin/update-rc.d ]; then
    update-rc.d smbd remove
    update-rc.d nmbd remove
fi
if [ -x /usr/bin/systemctl ]; then
    systemctl disable smbd
    systemctl disable nmbd
    systemctl mask smbd
    systemctl mask nmbd
fi
}

read_password()
{
if [ -n "$pass" ]; then
    return
fi
if ! IFS= read -r pass; then
    pass=""
fi
pass="${pass%$'\r'}"
}

addsambauser()
{
read_password
printf '%s\n%s\n' "$pass" "$pass" | smbpasswd -as "$user"
exit $?
}

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

changesambapasswd()
{
read_password
printf '%s\n%s\n' "$pass" "$pass" | smbpasswd -U "$user"
exit $?
}

# service works for starting and stopping on both sysV and systemd
startsamba()
{
if [ -x /usr/bin/systemctl ]; then
    MASKED=$(systemctl is-enabled smbd)
    systemctl unmask smbd
    systemctl unmask nmbd
fi

if [ -x /usr/sbin/service ]; then
    service smbd start
    service nmbd start
elif [ -x /usr/bin/systemctl ]; then
    systemctl start smbd
    systemctl start nmbd
fi

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

exit $?
}

stopsamba()
{
if [ -x /usr/sbin/service ]; then
    service smbd stop
    service nmbd stop
elif [ -x /usr/bin/systemctl ]; then
    systemctl stop smbd
    systemctl stop nmbd
fi

exit $?
}

main()
{
case $1 in
    startsamba)  startsamba
                 ;;
    stopsamba)  stopsamba
                 ;;
    enablesamba)  enablesamba
                 ;;
    disablesamba)  disablesamba
                 ;;
    addsambauser)  if [ -n "$3" ]; then
                       pass="$2"
                       user="$3"
                   else
                       user="$2"
                   fi
                   addsambauser
                   ;;
    removesambauser)  user="$2"
                      removesambauser
                   ;;
    changesambapasswd)  if [ -n "$3" ]; then
                            pass="$2"
                            user="$3"
                        else
                            user="$2"
                        fi
                        changesambapasswd
                   ;;
esac
}

main "$@"
