#!/bin/sh

[ -z "$ROOT" ] && ROOT=/www
CONFIG=$ROOT/config
SCRIPT=$ROOT/script

source $SCRIPT/utils/token.sh

readData() {
	eval "res=$3"

	echo -n "$1 [$res]: "
	read res
	if [ -z "$res" ] ; then
		eval "res=$3"
	fi

	eval "$2=$res"
}

API_CONFIG="$CONFIG/api.conf"
[ -f "$API_CONFIG" ] && source "$API_CONFIG"

readData "Cloud address" CLOUD "$CLOUD"

SCHEME=https
readData "Cloud scheme (http/https)" SCHEME "$SCHEME"

[ "$SCHEME" == https ] && PORT=443 || PORT=80
readData "Cloud port" PORT "$PORT"

CLOUD_HOST="$CLOUD"
[ "$SCHEME" == http -a "$PORT" != 80 ] && CLOUD_HOST="$CLOUD:$PORT"
[ "$SCHEME" == https -a "$PORT" != 443 ] && CLOUD_HOST="$CLOUD:$PORT"

CLOUD_ADDRESS="$SCHEME://$CLOUD_HOST/cloud/api/config"
readData "Config API address" CLOUD_ADDRESS "$CLOUD_ADDRESS"

AUTH_ADDRESS="$SCHEME://$CLOUD_HOST/cloud/api/session"
readData "Auth API address" AUTH_ADDRESS "$AUTH_ADDRESS"

wget -T5 -vO- $(getAuthHeader) $CLOUD_ADDRESS/ping

if [ $? -ne 0 ] ; then
proceed=N
readData "Couldn't reach cloud at $CLOUD_HOST. Continue? (y/N)" proceed "$proceed"
proceed="${proceed:0:1}"
[ "$proceed" != y -a "$proceed" != Y ] && exit 0
fi

cat > "$API_CONFIG" <<- EOM
CLOUD='$CLOUD'
SCHEME='$SCHEME'
PORT='$PORT'
CLOUD_ADDRESS='$CLOUD_ADDRESS'
AUTH_ADDRESS='$AUTH_ADDRESS'
EOM

echo "Update config"
sh -x $SCRIPT/update/update-ng-config.sh
