#!/bin/bash

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

# A unit file, not a mask (a link to /dev/null)
unit_exists()
{
local dir
for dir in /etc/systemd/system /usr/lib/systemd/system /lib/systemd/system; do
    [ -f "$dir/$1" ] && return 0
done
return 1
}

# Debian names the Samba services smbd and nmbd, Arch names them smb and nmb.
# The GUI picks its status unit by the same rule.
smb=smbd
nmb=nmbd
if [ ! -f /etc/init.d/smbd ] && ! unit_exists smbd.service && unit_exists smb.service; then
    smb=smb
    nmb=nmb
fi

# Run a step of a service action, remembering any failure so the action
# reports it after attempting the remaining steps
failed=0
try()
{
local status=0
"$@" || status=$?
if [ "$status" -ne 0 ]; then
    echo "Failed with status $status: $*" >&2
    failed=1
fi
}

# Some steps depend on the init system; fail when none can do the action
no_service_manager()
{
echo "No service manager found to $1 Samba" >&2
exit 1
}

# 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()
{
[ -x /usr/sbin/update-rc.d ] || [ -x /usr/bin/systemctl ] || no_service_manager enable
if [ -x /usr/sbin/update-rc.d ]; then
    # defaults installs links when missing; enable turns disabled ones back on
    try update-rc.d "$smb" defaults
    try update-rc.d "$nmb" defaults
    try update-rc.d "$smb" enable
    try update-rc.d "$nmb" enable
fi
if [ -x /usr/bin/systemctl ]; then
    try systemctl unmask "$smb"
    try systemctl unmask "$nmb"
    try systemctl enable "$smb"
    try systemctl enable "$nmb"
fi
exit "$failed"
}

disablesamba()
{
[ -x /usr/sbin/update-rc.d ] || [ -x /usr/bin/systemctl ] || no_service_manager disable
if [ -x /usr/sbin/update-rc.d ]; then
    # Keep disabled (K) links instead of removing them, so a package
    # upgrade running "update-rc.d ... defaults" does not re-enable Samba
    try update-rc.d "$smb" defaults
    try update-rc.d "$nmb" defaults
    try update-rc.d "$smb" disable
    try update-rc.d "$nmb" disable
fi
if [ -x /usr/bin/systemctl ]; then
    try systemctl disable "$smb"
    try systemctl disable "$nmb"
    try systemctl mask "$smb"
    try systemctl mask "$nmb"
fi
exit "$failed"
}

# Passwords come only from standard input, never from arguments, which
# other users can read in the process list
read_password()
{
# read fails on a last line without a newline but still sets pass
IFS= read -r pass || true
pass="${pass%$'\r'}"
if [ -z "$pass" ]; then
    echo "No password was given on standard input" >&2
    exit 1
fi
}

addsambauser()
{
read_password
# smbpasswd -a changes the password of an existing account, so add the account
# only once Samba reports that it does not exist. The lock, which only root can
# open, keeps two additions from both passing the check.
umask 077
exec 9>/run/mx-samba-config.lock && flock 9 || exit 1
local lookup accounts found list_errors
if lookup=$(pdbedit -u "$user" 2>&1 >/dev/null); then
    echo "Samba user $user already exists" >&2
    exit 3
fi
# pdbedit reports a lookup that failed for any reason as not found, so confirm
# the absence against the account list too
list_errors=$(mktemp) || exit 1
trap 'rm -f "$list_errors"' EXIT
if grep -qx 'Username not found!' <<<"$lookup" && accounts=$(pdbedit --list 2>"$list_errors"); then
    found=$(awk -F: -v user="$user" 'tolower($1) == tolower(user) { found = 1 } END { print found ? "yes" : "no" }' <<<"$accounts")
fi
if [ "$found" = yes ]; then
    echo "Samba user $user already exists" >&2
    exit 3
elif [ "$found" != no ]; then
    printf 'Could not check whether Samba user %s exists\n%s\n' "$user" "$lookup" >&2
    cat "$list_errors" >&2
    exit 1
fi
printf '%s\n%s\n' "$pass" "$pass" | smbpasswd -as "$user"
exit $?
}

removesambauser()
{
# Delete the account only if it is still the one that was selected, which
# the caller identifies by its SID
local sid
sid=$(pdbedit -v -u "$user" 2>/dev/null | sed -n 's/^User SID:[[:space:]]*//p')
if [[ -z $sid || $sid != "$expected_sid" ]]; then
    echo "Samba user $user is no longer the account that was selected" >&2
    exit 1
fi
pdbedit --delete "$user"
exit $?
}

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

# service works for starting and stopping on both sysV and systemd
startsamba()
{
# A masked unit cannot start, and disablesamba masks the units, so unmask each
# masked one for the start and mask it again afterwards, even if the start
# fails, keeping each unit's own setting
declare -gA persistent_mask=() runtime_mask=()
local unit state
[ -x /usr/sbin/service ] || [ -x /usr/bin/systemctl ] || no_service_manager start
if [ -x /usr/bin/systemctl ]; then
    trap restore_masks EXIT
    trap 'failed=1; exit 1' HUP INT TERM
    for unit in "$smb" "$nmb"; do
        # A persistent mask hides a runtime one, so check again after removing it
        read_unit_state "$unit"
        if [ "$state" = masked ]; then
            persistent_mask[$unit]=1
            try systemctl unmask "$unit"
            read_unit_state "$unit"
        fi
        if [ "$state" = masked-runtime ]; then
            runtime_mask[$unit]=1
            try systemctl unmask --runtime "$unit"
        fi
    done
fi

if [ -x /usr/sbin/service ]; then
    try service "$smb" start
    try service "$nmb" start
elif [ -x /usr/bin/systemctl ]; then
    try systemctl start "$smb"
    try systemctl start "$nmb"
fi

exit "$failed"
}

# Sets state to the unit file state, in the caller's scope. is-enabled exits
# nonzero for states such as disabled and masked, so judge the lookup by the
# state it prints: none, not-found and bad mean it failed.
read_unit_state()
{
state=$(systemctl is-enabled "$1")
case $state in
    ''|not-found|bad)
        echo "Could not read the state of $1${state:+ ($state)}" >&2
        failed=1
        ;;
esac
}

restore_masks()
{
local unit
# Finish restoring every unit even if another signal arrives
trap '' HUP INT TERM
for unit in "${!runtime_mask[@]}"; do
    try systemctl mask --runtime "$unit"
done
for unit in "${!persistent_mask[@]}"; do
    try systemctl mask "$unit"
done
# Report a failure to restore a mask too
exit "$failed"
}

stopsamba()
{
[ -x /usr/sbin/service ] || [ -x /usr/bin/systemctl ] || no_service_manager stop
if [ -x /usr/sbin/service ]; then
    try service "$smb" stop
    try service "$nmb" stop
elif [ -x /usr/bin/systemctl ]; then
    try systemctl stop "$smb"
    try systemctl stop "$nmb"
fi

exit "$failed"
}

main()
{
case $1 in
    startsamba)  startsamba
                 ;;
    stopsamba)  stopsamba
                 ;;
    enablesamba)  enablesamba
                 ;;
    disablesamba)  disablesamba
                 ;;
    addsambauser)  if [ $# -ne 2 ]; then
                       echo "Usage: $0 addsambauser USER (password on standard input)" >&2
                       exit 2
                   fi
                   user="$2"
                   addsambauser
                   ;;
    removesambauser)  user="$2"
                      expected_sid="$3"
                      removesambauser
                   ;;
    changesambapasswd)  if [ $# -ne 2 ]; then
                            echo "Usage: $0 changesambapasswd USER (password on standard input)" >&2
                            exit 2
                        fi
                        user="$2"
                        changesambapasswd
                   ;;
esac
}

main "$@"
