#!/bin/bash
set -e

printf "Host name: " >&2
if [ "$1" ]; then
    host="$1"; shift
    echo "$host"
else
    read host
fi

if ! grep -Fq "." <<< "$host"; then host=$host.mit.edu; fi

printf "User: " >&2
if [ "$1" ]; then
    user="$1"; shift
    echo "$user"
else
    read user
fi

while read attr value; do
    echo "$attr" "$value"
    case "$attr" in
	dn:) user_dn=$value;;
	uid:) user=$value;;
	uidNumber:) uid=$value;;
	gidNumber:) gid=$value;;
	homeDirectory:) home=$value;;
    esac
done < <(ldapsearch -LLL -x -h scripts.mit.edu -b ou=People,dc=scripts,dc=mit,dc=edu "(uid=$user)" dn uid uidNumber gidNumber homeDirectory | perl -0pe 's/\n //g;')

printf "Docroot: $home/web_scripts" >&2
read subdir

tmpfile=$(mktemp -t vhostadd.XXXXXX) || exit $?
trap 'rm -f "$tmpfile"' EXIT

cat <<EOF > "$tmpfile"
dn: apacheServerName=$host,ou=VirtualHosts,dc=scripts,dc=mit,dc=edu
objectClass: apacheConfig
objectClass: top
apacheServerName: $host
EOF

if [ "${host%mit.edu}" != "$host" ]; then
    cat <<EOF >> "$tmpfile"
apacheServerAlias: ${host%.mit.edu}
EOF
fi

cat <<EOF >> "$tmpfile"
apacheDocumentRoot: $home/web_scripts$subdir
apacheSuexecUid: $uid
apacheSuexecGid: $gid

dn: scriptsVhostName=$host,ou=VirtualHosts,dc=scripts,dc=mit,dc=edu
objectClass: scriptsVhost
objectClass: top
scriptsVhostName: $host
EOF

if [ "${host%mit.edu}" != "$host" ]; then
    cat <<EOF >> "$tmpfile"
scriptsVhostAlias: ${host%.mit.edu}
EOF
fi

cat <<EOF >> "$tmpfile"
scriptsVhostAccount: $user_dn
scriptsVhostDirectory: ${subdir#/}
EOF

exec ldapvi --bind sasl -Y GSSAPI -h scripts4.mit.edu -b dc=scripts,dc=mit,dc=edu --add --in "$tmpfile"
