#!/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/>.

# Testing:
# testparm -s -v

set -e

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

OMV_SAMBA_CONFIG=${OMV_SAMBA_CONFIG:-"/etc/samba/smb.conf"}
OMV_SAMBA_LDAP_SSL=${OMV_SAMBA_LDAP_SSL:-"off"}
OMV_SAMBA_LDAP_PASSWDSYNC=${OMV_SAMBA_LDAP_PASSWDSYNC:-"yes"}
OMV_SAMBA_LDAP_LDAPSAMTRUSTED=${OMV_SAMBA_LDAP_LDAPSAMTRUSTED:-"no"}
OMV_SAMBA_LDAP_IDMAPUID=${OMV_SAMBA_LDAP_IDMAPUID:-"10000-20000"}
OMV_SAMBA_LDAP_IDMAPGID=${OMV_SAMBA_LDAP_IDMAPGID:-"10000-20000"}

[ "$(omv_config_get "//services/smb/enable")" = "0" -o \
  "$(omv_config_get "//services/ldap/enable")" = "0" ] && exit 0

rootbindpw=$(omv_config_get "//services/ldap/rootbindpw")

xmlstarlet sel -t -m "//services/ldap" \
  -o "#======================= LDAP Settings =======================" -n \
  -o "security = user" -n \
  -v "concat('passdb backend = ldapsam:ldap://',host)" -n \
  -v "concat('ldap suffix = ',base)" -n \
  -v "concat('ldap admin dn = ',rootbinddn)" -n \
  -v "concat('ldap user suffix = ',usersuffix)" -n \
  -v "concat('ldap group suffix = ',groupsuffix)" -n \
  -o "ldap ssl = ${OMV_SAMBA_LDAP_SSL}" -n \
  -o "ldap passwd sync = ${OMV_SAMBA_LDAP_PASSWDSYNC}" -n \
  -o "ldapsam:trusted = ${OMV_SAMBA_LDAP_LDAPSAMTRUSTED}" -n \
  -o "idmap uid = ${OMV_SAMBA_LDAP_IDMAPUID}" -n \
  -o "idmap gid = ${OMV_SAMBA_LDAP_IDMAPGID}" -n \
  ${OMV_CONFIG_FILE} | xmlstarlet unesc >> ${OMV_SAMBA_CONFIG}

smbpasswd -w ${rootbindpw} 2>&1
