#!/bin/bash

set -o errexit
set -o nounset

# SOE4 bootstrap script:
# retrieves MANIFEST and all files specified within
# runs the first file (usually stage1)

#CHANGELOG
#0.50	initial
#0.51	pass authentication to other stages
#0.52	comments update
#0.53	save password entered manually
#0.54	create dir for saved passwords if needed
#0.55	use tmpfs to store SECRET_FILE if needed
#0.56	allow override of the base URL
#0.57	allow for independent testing of DEV version
#0.60	move to master.clearcable.net (URL update)
#0.61	restyle according to https://kb.clearcable.ca/KB/ProgrammingStyleStandards
#0.7.0	move to SOE4.3 master.clearcable.net under HTTPS

declare -r SOE_INSTALL_API=3
export SOE_INSTALL_API
declare -r SECRET_FILE='/usr/local/etc/soe-install.secret'
declare -r URL_DEFAULT='https://setup.clearcable.net'

if [[ -n "${URL+xxx}" ]]; then
	URL_BASE="$URL"
else
	URL_BASE="$URL_DEFAULT"
fi
export URL_BASE

if [[ -n "${DEV+xxx}" ]]; then
	DEV_SUFFIX='.dev'
else
	DEV_SUFFIX=''
fi

if [[ -n "${VERBOSE+xxx}" ]]; then
	set -o xtrace
fi

USER=$(basename $0)
if [[ -s $SECRET_FILE ]]; then
	echo "using shared secret from file $SECRET_FILE"
	USER=$(awk -F: '{print $1}' $SECRET_FILE)
	PASS=$(awk -F: '{print $2}' $SECRET_FILE)
else
	echo -n 'password: '
	read PASS

	SECRET_DIR=$(dirname $SECRET_FILE)
	if [[ ! -d $SECRET_DIR ]]; then
		mount -t tmpfs tmpfs '/usr/local'
		mkdir $SECRET_DIR
	fi
	touch $SECRET_FILE
	chmod 640 $SECRET_FILE
	echo "$USER:$PASS" > $SECRET_FILE
fi

CURL="curl --silent --user $USER:$PASS"
export CURL

INSTALLER_DIR=$(mktemp --directory)
cd $INSTALLER_DIR
export INSTALLER_DIR

$CURL --output MANIFEST "$URL_BASE/installer/MANIFEST$DEV_SUFFIX"
echo -n "MANIFEST:"
for FILE in $(cat MANIFEST); do
	$CURL --remote-name $URL_BASE/installer/$FILE
	echo -n " $FILE"
done
echo

ENTRY_STAGE=$(head --lines=1 MANIFEST) # usually "stage1"
NEXT_STAGE=$(head --lines=2 MANIFEST|tail --lines=1) # usually "stage2"
export NEXT_STAGE
bash $ENTRY_STAGE $*
rm --recursive $INSTALLER_DIR
