#!/bin/sh
set -e

usage () {
    cat <<END
usage:
   hippotat-setup-permissions client
   hippotat-setup-permissions server
   hippotat-setup-permissions revoke
END
}

case "$1.$#" in
client.1|server.1|revoke.1)	cs="$1" ;;
--help.*)		usage; exit 0 ;;
*)
    echo >&2 "bad usage: unknown arguments/options"
    usage >&2
    exit 12
    ;;
esac

DAEMON=/usr/sbin/hippotatd
USER=_hippotat
GROUP=_hippotat
test -e /etc/default/hippotatd && . /etc/default/hippotatd

uid=$(id -u "$USER")

if ! test -e /etc/userv/services.d/ipif; then
    ln -s ../services-available/ipif /etc/userv/services.d/ipif
    echo 'enabled ipif userv service'
fi

case "$USER" in
    root)
	echo "USER=root, revoking permissions"
	cs=revoke
	;;
esac

remove_file () {
    if test -e "$f"; then
	echo "Removing $f"
    fi
    rm -f "$f" "$f~new~"
}
start_file () {
    exec 3>"$f~new~"
    echo >&3 '# created by hippotat-setup-permissions'
}
install_file () {
    mv -f "$f~new~" "$f"
    echo "Installed $f"
}

f=/etc/authbind/byuid/$uid
case "$cs" in
    client|revoke)
	remove_file
	;;
    server)
	start_file
	$DAEMON --print-config port,addrs | \
	    while read port addrs; do
		for addr in $addrs; do
		    echo >&3 "$addr,$port"
		done
	    done
	install_file
	;;
esac

permit_ipif () {
    user_spec=$1
    printf >&3 "permit %s ifname %s local %s" "$user_spec" "$ifname" "$vaddr"
    for vnet in $vnets; do
	printf >&3 " remote %s" "$vnet"
    done
    echo >&3
}

f=/etc/userv/ipif-access/hippotat
start_file
case "$cs" in
    *server*)
	$DAEMON --print-config ifname_server,vaddr,vnetwork,vroutes | \
	    while read ifname vaddr vnets; do
		permit_ipif "user $USER" 
	    done
	;;
esac
case "$cs" in
    *client*)
	hippotat --print-config ifname_client,client,vnetwork,vroutes | \
	    while read ifname vaddr vnets; do
		permit_ipif "group $GROUP" 
	    done
	;;
esac

if test -s "$f~new~"; then
    install_file
else
    case "$cs" in
	revoke) ;;
	*) echo 'No hippotat configuration.' ;;
    esac
    remove_file
    echo "Revoked virtual network interface permissions."
fi

if grep -q '^permit user ' $f; then
    echo "Granted user $USER permissions needed for running the server."
fi

if grep -q '^permit group ' $f; then
    echo "Granted group $GROUP permissions needed for running the client."
    echo "Consider putting yourself in that group!"
fi
