#!/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-2018 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_SECURITY=${OMV_SAMBA_SECURITY:-"user"}
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_config_get "//services/smb/enable")" != "1" -o \
  "$(omv_config_get "//services/ldap/enable")" != "1" ] && exit 0

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

xmlstarlet sel -t -m "//services/ldap" \
  -o "#======================= LDAP Settings =======================" -n \
  -o "security = ${OMV_SAMBA_SECURITY}" -n \
  -o "passdb backend = ldapsam:ldap" -i "enablessl[. = '1']" -o "s" -b -o "://" -v host -i "string-length(port) > 0" -v "concat(':',port)" -b -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 \
  ${OMV_CONFIG_FILE} | xmlstarlet unesc >> ${OMV_SAMBA_CONFIG}

smbpasswd -w "${rootbindpw}" 2>&1
