#!/bin/bash
#
# This is a helper script for travis-ci builds and our own FreeBSD test machine.
# It is not meant to be used by end-users
#

if [ ! -d extras ]; then
	echo "This tool is supposed to be run from the source root, so ~/unrealircd-4.0.x or similar"
	exit 1
fi

set -x

# Take default settings as a starter..
cp extras/build-tests/nix/configs/default ./config.settings

# Libtool is required for the other options..
# Also for our FreeBSD machine we have to uninstall some stuff since a clean
# environment is not guaranteed...
if [ "$OSTYPE" = "linux-gnu" ]; then
	sudo apt-get install libtool -qq
elif [[ "$OSTYPE" == "freebsd"* ]]; then
	sudo pkg install -y libtool
	sudo pkg remove -y c-ares
elif [[ "$OSTYPE" == "darwin"* ]]; then
	brew update
	brew install openssl
else
	echo "OS not correctly detected ($OSTYPE). Aborting."
	exit 1
fi

echo "*****************************************************************"
echo "SELECTED BUILD OPTIONS: $*"
echo "*****************************************************************"

while [ "$1" ]
do
	echo "Processing option $1..."
	if [ "$1" = "system-cares" ]; then
		if [ "$OSTYPE" = "linux-gnu" ]; then
			sudo apt-get install libc-ares-dev -qq
		elif [[ "$OSTYPE" == "freebsd"* ]]; then
			sudo pkg install -y c-ares
		elif [[ "$OSTYPE" == "darwin"* ]]; then
			brew install c-ares
		fi
	elif [ "$1" = "system-curl" ]; then
		echo 'REMOTEINC=1' >>config.settings
		if [ "$OSTYPE" = "linux-gnu" ]; then
			sudo apt-get install libcurl4-openssl-dev -qq
			echo 'CURLDIR=/usr' >>config.settings
		elif [[ "$OSTYPE" == "freebsd"* ]]; then
			sudo pkg install -y curl
			echo 'CURLDIR=/usr/local' >>config.settings
		elif [[ "$OSTYPE" == "darwin"* ]]; then
			brew install c-ares curl
			echo 'CURLDIR=/usr/local/opt/curl' >>config.settings
		fi
	elif [ "$1" = "local-curl" ]; then
		if [ "$OSTYPE" = "linux-gnu" ]; then
			sudo apt-get remove libcurl4-openssl-dev libcurl3-gnutls libcurl3 -qq
		elif [[ "$OSTYPE" == "freebsd"* ]]; then
			sudo pkg remove -y curl #NOTE: unfortunately this also removes 'git' :D
		elif [[ "$OSTYPE" == "darwin"* ]]; then
			echo "No need to remove curl since it's not installed. Or at least I hope so..."
		fi
		echo 'REMOTEINC=1' >>config.settings
		echo "CURLDIR=`pwd`/extras/curl" >>config.settings
	else
		echo "Unknown option $1"
		exit 1
	fi
	shift
done
