#!/bin/sh
set -e

WRITE=0
FORCE=0
PREFIX=
: "${SCRIPT_PATH:=$(dirname "$0")}"

while [ -n "$1" ]
do
	case "$1" in
		-h | --help)
			printf '\033[0mUsage: \033[1m%s\033[0m [ \033[1m--help\033[0m ] [ \033[1m--install\033[0m [ \033[1m--force\033[0m ] ] [ \033[1m--prefix\033[0m \033[4mDIR\033[0m ]\n' "${ARGV0:-$0}"
			printf '\n'
			printf '   This program will write \033[4m/etc/rc.conf.d/netif\033[0m, \033[4m/etc/rc.conf.d/routing\033[0m and \033[4m/etc/resolv.conf\033[0m,\n'
			printf '   using the settings from the OpenNebula context disk image.\n'
			printf '\n'
			printf '   \033[1m--help   \033[0m   \033[0m	Show this help text.\n'
			printf '   \033[1m--install\033[0m   \033[0m	Write files for first boot.\n'
			printf '   \033[1m--force  \033[0m   \033[0m	Overwrite files if already exist.\n'
			printf '   \033[1m         \033[0m   \033[0m	(NOTE: \033[4mresolv.conf\033[0m will always be overwritten if \033[4mnetif\033[0m is written)\n'
			printf '   \033[1m--prefix \033[0;4mDIR\033[0m	Write to directory specified in \033[4mDIR\033[0m.\n'
			printf '\n'
			return;;
		--install)
			if [ "$WRITE" = 1 ]
			then
				printf '\033[0m%s: \033[1m--install\033[0m is specified more than once.\n' "${ARGV0:-$0}" >&2
				exit 2
			fi
			WRITE=1
			shift;;
		--force)
			if [ "$FORCE" = 1 ]
			then
				printf '\033[0m%s: \033[1m--force\033[0m is specified more than once.\n' "${ARGV0:-$0}" >&2
				exit 2
			fi
			FORCE=1
			shift;;
		--prefix)
			if [ -n "$PREFIX" ]
			then
				printf '\033[0m%s: \033[1m--prefix\033[0m is specified more than once.\n' "${ARGV0:-$0}" >&2
				exit 2
			fi
			if [ -z "$2" ]
			then
				printf '\033[0m%s: \033[1m--prefix\033[0m specified without \033[4mDIR\033[0m.\n' "${ARGV0:-$0}" >&2
				exit 2
			fi
			PREFIX="$2"
			shift 2;;
		*)
			printf '\033[0m%s: Unexpected argument \033[1m%s\033[0m.\n' "${ARGV0:-$0}" "$1" >&2
			exit 2
	esac
done

if [ "$WRITE" = 1 ] && [ "$FORCE" = 0 ]
then
	if [ -f "$PREFIX/etc/rc.conf.d/netif" ] || [ -f "$PREFIX/etc/rc.conf.d/routing" ]
	then
		printf '\033[0m%s: Files \033[4mnetif\033[0m or \033[4mrouting\033[0m already exist in \033[4m/etc/rc.conf.d\033[0m, and \033[1m--force\033[0m not specified.\n' "${ARGV0:-$0}" >&2
		exit 4
	fi
fi

[ "$WRITE" = 0 ] && OUT='/dev/stdout'
mkdir -p "$PREFIX/etc/rc.conf.d"

# Shellcheck apparently thinks we're changing $SCRIPT_PATH here, but we're not ..?
# shellcheck disable=SC2031
( echo "# $PREFIX/etc/rc.conf.d/netif"  ; . "${SCRIPT_PATH}/netconf-network.sh"; ) >"${OUT:-${PREFIX}/etc/rc.conf.d/netif}"
# shellcheck disable=SC2031
( echo "# $PREFIX/etc/rc.conf.d/routing"; . "${SCRIPT_PATH}/netconf-routing.sh"; ) >"${OUT:-${PREFIX}/etc/rc.conf.d/routing}"
# shellcheck disable=SC2031
( echo "# $PREFIX/etc/resolv.conf"      ; . "${SCRIPT_PATH}/netconf-resolv.sh";  ) >"${OUT:-${PREFIX}/etc/resolv.conf}"
