#!/bin/sh -e
#
# Univention Samba
#  helper script: synchronize netlogon and account policies
#
# Copyright 2004-2014 Univention GmbH
#
# http://www.univention.de/
#
# All rights reserved.
#
# The source code of this program is made available
# under the terms of the GNU Affero General Public License version 3
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this program provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention and not subject to the GNU AGPL V3.
#
# In the case you use this program under the terms of the GNU AGPL V3,
# the program is provided 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <http://www.gnu.org/licenses/>.

eval "$(/usr/sbin/univention-config-registry shell ldap/master server/role hostname samba/netlogon/sync)"

if [ "$server_role" = "domaincontroller_master" -o "$server_role" = "memberserver" ]; then
	exit 0
fi

PDC=$ldap_master
NETLOGON_PATH=/var/lib/samba/netlogon
ACCOUNT_PATH=/var/lib/samba/account-policy
ACCOUNT_FILE=policy.txt
RSYNC_OPTS="--delete"

if [ "$samba_netlogon_sync" = "none" ] ; then
	exit 0
fi
if [ "$samba_netlogon_sync" = "download" ] ; then
	RSYNC_OPTS=""
fi

# copy netlogon share
stderr_ssh_rsync=$(mktemp)
trap "rm -f '$stderr_ssh_rsync'" EXIT

mkdir -p $NETLOGON_PATH
if ! univention-ssh-rsync /etc/machine.secret -aAz $RSYNC_OPTS "$hostname\$@$PDC:$NETLOGON_PATH/" "$NETLOGON_PATH" 2>"$stderr_ssh_rsync"; then
	cat "$stderr_ssh_rsync" >&2
	exit 1
fi

mkdir -p $ACCOUNT_PATH
if ! univention-ssh-rsync /etc/machine.secret -aAz $RSYNC_OPTS "$hostname\$@$PDC:$ACCOUNT_PATH/" "$ACCOUNT_PATH" 2>"$stderr_ssh_rsync"; then
	cat "$stderr_ssh_rsync" >&2
	exit 1
fi

if [ -e "$ACCOUNT_PATH/$ACCOUNT_FILE" ]; then
	cat "$ACCOUNT_PATH/$ACCOUNT_FILE" | /usr/share/univention-samba/set_account_policy_from_pdbedit
fi
