#!/bin/sh
#
# This file is part of OpenMediaVault.
#
# @license   http://www.gnu.org/licenses/gpl.html GPL Version 3
# @author    Volker Theile <volker.theile@openmediavault.org>
# @copyright Copyright (c) 2009-2012 Volker Theile
#
# OpenMediaVault is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# OpenMediaVault is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with OpenMediaVault. If not, see <http://www.gnu.org/licenses/>.

set -e

. /etc/default/openmediavault
. /usr/share/openmediavault/scripts/helper-functions

# Get some shadow password suite configurations
UID_MIN=$(awk '/^UID_MIN/ {print $2}' /etc/login.defs)
UID_MAX=$(awk '/^UID_MAX/ {print $2}' /etc/login.defs)

# Create the configuration files
omv-mkconf samba

# Update the user database
getent passwd | /usr/sbin/mksmbpasswd > /etc/samba/smbpasswd
pdbedit -i smbpasswd -e tdbsam
rm /etc/samba/smbpasswd
xmlstarlet sel -t -m "//system/usermanagement/users/user" \
  -v "concat(uuid,' ',name)" -i "position() != last()" -n -b \
  ${OMV_CONFIG_FILE} | xmlstarlet unesc |
  while read uuid name; do
	  uid=$(id -u ${name} || true)
	  [ -z "${uid}" ] && continue
	  # Do not process system users
	  [ ${uid} -lt ${UID_MIN} -o ${uid} -gt ${UID_MAX} ] && continue
	  # Add a user into the SAM database
	  password=$(omv_config_get "//system/usermanagement/users/user[uuid='${uuid}']/password")
	  (echo ${password}; echo ${password}) | pdbedit -at ${name} 2>&1
  done

# Enable/disable service
if [ "$(omv_config_get "//services/smb/enable")" = "0" ]; then
	update-rc.d samba disable 2>&1
else
	update-rc.d samba enable 2>&1
fi

exit 0
