#!/bin/sh

print_syntax ()
{
	echo "Syntax: $0 [-i IPADDRESS]"
	echo "Please use the IP address of the machine where minipot is supposed to run"
	echo "The -i option is mandatory if the your machine has more than one routable IP address"
}

# $1 the IP address
_inject_ip()
{
	local ip="$1"
	# configure consul
	sysrc consul_args="-advertise $ip"
}

# $1 the IP address
_find_netif()
{
	local ifs ip
	ip="$1"
	ifs="$(ifconfig | grep '^[a-z]' | cut -f 1 -d ":" | tr '\n' ' ')"
	for netif in $ifs ; do
		if ifconfig "$netif" | grep -q -F " $ip " ; then
			echo $netif
			return
		fi
	done
}

while getopts :i:h arg; do
	case $arg in
		h)
			print_syntax
			exit 0
			;;
		i)
			ip="$OPTARG"
			netif="$( _find_netif "$ip" )"
			if [ -z "$netif" ]; then
				echo "$ip is not bound to any interface - aborting"
				exit 1
			fi
			;;
		?)
			print_syntax
			exit 1
			;;
	esac
done

if ! grep -c "^kern.racct.enable=1" /boot/loader.conf ; then
	echo kern.racct.enable=1 >> /boot/loader.conf
fi

if [ ! -e /etc/pf.conf.potbkp ] && [ -e /etc/pf.conf ]; then
	cp /etc/pf.conf /etc/pf.conf.potbkp
fi
pot init

sysrc nomad_user="root"
sysrc nomad_dir="/var/tmp/nomad"
sysrc nomad_env="PATH=/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/sbin:/bin"
sysrc nomad_args="-config=/usr/local/etc/nomad/minipot-server.hcl -data-dir=/var/tmp/nomad"
[ -n "$netif" ] && sysrc nomad_args+=" -network-interface=$netif"
sysrc consul_enable="YES"
sysrc nomad_enable="YES"
sysrc traefik_enable="YES"
sysrc traefik_conf="/usr/local/etc/minipot-traefik.toml"

mkdir -p /var/log/consul
mkdir -p /var/log/nomad
touch /var/log/consul/consul.log
touch /var/log/nomad/nomad.log
touch /var/log/traefik.log
touch /var/log/traefik-access.log
chown traefik:traefik /var/log/traefik.log
chown traefik:traefik /var/log/traefik-access.log

if [ -n "$ip" ]; then
	_inject_ip "$ip"
fi

