#!/bin/sh -efu

. girar-sh-functions

. shell-error
. shell-quote

[ -n "${GIRAR_USER-}" ] ||
        fatal 'GIRAR_USER undefined'

read -t 1 repository
repository="$(girar-normalize-repo-name "$repository")"

enable -f /usr/lib/bash/lockf lockf
builtin lockf -v "$GIRAR_ACL_CONF_DIR"

. girar-sh-tmpdir
cd "$tmpdir"

mkdir list

# Copy all current acl files to tmpdir.
cd "$GIRAR_ACL_CONF_DIR"
find -maxdepth 1 -type f -name 'list.*' \
	-exec cp -at "$tmpdir/list" -- \{\} \+
cd - > /dev/null

# Save old acl files for the later analysis.
cp -a list list.orig

cd list
if girar-acl-apply-changes "$repository" . > ../log 2>&1 &&
   find -maxdepth 1 -type f -name 'list.*' \
   -exec cp -at "$GIRAR_ACL_CONF_DIR" -- \{\} \+; then
	status=COMPLETE
else
	status=ABORTED
fi
cd - > /dev/null

rsync -rlt -- "$GIRAR_ACL_CONF_DIR/" "$GIRAR_ACL_PUB_DIR/"

email="$(girar-get-email-address "$GIRAR_USER")"
robot="Girar ACL robot <girar-acl@$EMAIL_DOMAIN>"
if [ "$status" = COMPLETE ]; then
	to="$robot"
	cc=
else
	to="$email"
	cc="$robot"
fi
cat > msg <<EOF
From: $robot
To: $to
Cc: $cc
X-Incominger: acl
Subject: [girar-acl] $status $repository
Content-Type: text/plain; charset=us-ascii

Dear $(printf %s "$email" | sed -n 's/^"\([^"]\+\)".*/\1/p')!

Result of your acl command(s) is listed below:

EOF
cat log >> msg
cat >> msg <<EOF

Summary: ACL change transaction $status.


-- 
Rgrds, your Girar ACL robot

EOF

/usr/sbin/sendmail -i -t <msg

girar-acl-notify-changes list.orig "$GIRAR_ACL_CONF_DIR"
