#!/bin/bash
# Helper functions used to interact with the installer database.
# You should source it in your programs:
# 	. /path/to/wizard

: ${DIALOG=dialog}

: ${DIALOG_OK=0}
: ${DIALOG_CANCEL=1}
: ${DIALOG_HELP=2}
: ${DIALOG_EXTRA=3}
: ${DIALOG_ITEM_HELP=4}
: ${DIALOG_ESC=255}

: ${SIG_NONE=0}
: ${SIG_HUP=1}
: ${SIG_INT=2}
: ${SIG_QUIT=3}
: ${SIG_KILL=9}
: ${SIG_TERM=15}

set -e
set -o pipefail

# list of questions which will be asked when calling wiz_ask
WIZ_BUFFER=""
# list of questions that will be forcibly asked again
WIZ_UNSEEN=""

INSTALLER_DEBUG=${INSTALLER_DEBUG:="no"}
CURRENT_ADDON="$(dirname "$(cd "$(dirname "$0")" ; pwd)")"

hinit() {
	rm -f /tmp/hashmap.$1
	touch /tmp/hashmap.$1
}

hput() {
    echo "$2 $3" >> /tmp/hashmap.$1
}

hget() {
    grep "^$2 " /tmp/hashmap.$1 | awk '{ print $2 };'
}

hinit WIZ_STATES_QUESTIONS

wiz_debug() {
	if [ ! "${INSTALLER_DEBUG}" = "no" ]; then
		echo "[debug] $1" >&2
	fi
}

wizard() {
	STATE="$1"
	while true; do
		wiz_debug "STATE=$STATE OLDSTATE=$OLDSTATE"
		OLDSTATE="$STATE"
		_wiz_reset "$STATE"
		state_machine "$STATE"
		if [ "$OLDSTATE" = "$STATE" ]; then
			STATE="same-state"
		fi
	done
}

# Makes all questions asked during this state as unseen again.
# This is usually called when the user goes back to a state that has already been seen.
_wiz_reset() {
	local state="$1"
	wiz_debug "state=$state state_buffer=$(hget WIZ_STATES_QUESTIONS "$state")"
	for question in $(hget WIZ_STATES_QUESTIONS "$state") ; do
		wiz_unseen "$question"
	done
	hput WIZ_STATES_QUESTIONS "$state" ""
}

wiz_random_password() {
	local size=${1:=32}
	echo $(< /dev/urandom tr -dc A-Za-z0-9 | head -c${size};echo;)
}

wiz_set() {
	local key="$1"
	local value="$2"
	wiz_debug "wiz_set key=$key value=$value"
	sed -i "s|${key} .*||" "$DATABASE"
	echo "${key} ${value}" >> "$DATABASE"
}

wiz_get_or_set() {
	local key="$1"
	local value="$2"
	wiz_debug "wiz_get_or_set key=$key value=$value"
	wiz_get "$key" &>/dev/null || wiz_set "$key" "$value"
}

wiz_ask() {
	wiz_debug "wiz_ask"
	for question in $WIZ_BUFFER ; do
		if ! wiz_dialog "$question" ; then
			wiz_clear
			return 1;
		fi
	done
	wiz_clear
}

# Clear the buffer of questions
wiz_clear() {
	wiz_debug "wiz_clear"
	WIZ_BUFFER=""
}

# Triggers the display of a new dialog
# Returns 0 if success, 1 if user canceled
# e.g.:
#
# 	wiz_dialog("mysql/db_host")
wiz_dialog() {
	local key="$1"
	local kind=$(wiz_meta "$key" "type")
	local title=$(wiz_meta "$key" "title")
	local description=$(wiz_meta "$key" "description")
	local default="$(wiz_get "$key" || wiz_meta "$key" "default")"

	wiz_debug "wiz_dialog key='$key' type='${kind}' default='${default}' title='${title}' description='${description}'"

	case "$kind" in
		"select")
			local choices=$(wiz_meta "$key" "choices")
			local args=""
			local cmd="$DIALOG --stdout ${args} --clear --title \"$key\" --default-item \"${default}\" --menu \"$description\n\n$title\" 0 0 4 $choices"
			wiz_debug "cmd=${cmd}"
			result=$(eval $cmd)
			status=$?
			;;

		"string")
			local cmd="$DIALOG --stdout --clear --title \"$key\" --inputbox \"$description\n\n$title\" 16 51 \"${default}\""
			wiz_debug "cmd=${cmd}"
			result=$(eval $cmd)
			status=$?
			;;

		"password")
			local cmd="$DIALOG --stdout --clear --title \"$key\" --insecure --passwordbox \"$description\n\n$title\" 16 51"
			wiz_debug "cmd=${cmd}"
			result="$(eval $cmd)"
			status=$?
			# defaults to existing password if none given
			if [ $status -eq 0 ] && [ "$result" = "" ]; then
				result="$default"
			fi
			;;

		"boolean")
			if $DIALOG --title "$key" --clear $([ "$default" = "true" ] || echo "--defaultno") \
				--yesno "$description\n\n$title" 15 61 ; then
				result="true"
			else
				result="false"
			fi
			status=${DIALOG_OK}
			;;
		*)
			echo "unknown dialog type: ${kind}"
			return 1
			;;
	esac

	case $status in
		$DIALOG_OK)
			wiz_set "$key" "$result"
			return 0
			;;
		*)
			return 1
			;;
	esac
}

# Returns the path to the current wizard's "templates" file.
wiz_template() {
	echo "${CURRENT_ADDON}/templates"
}

# Fetch a property from a quesion from the "templates" file.
# Outputs the result on STDOUT.
# e.g.
# 	wiz_meta("mysql/db_host", "description")
wiz_meta() {
	local key="$1"
	local attribute="$2"
	wiz_debug "wiz_meta key=$key property=${attribute}"
	IFS='/' read -a array <<< "$key"
	local addon="${array[0]}"
	local tmpdir=$(mktemp -d)
	local addon_templates=$(wiz_template "${addon}")

	csplit -zs -f ${tmpdir}/item "$addon_templates" /^Template:/ {*}
	local template=""
	for file in ${tmpdir}/item* ; do
		if grep -q "Template: ${key}" ${file} ; then
			template="$file"
			break
		fi
	done

	if [ -z "$template" ] ; then exit 1 ; fi

	case "$attribute" in
		"type")
			sed -n -r 's|^Type: (.+)$|\1|p' "$template"
			;;
		"title")
			sed -n -r 's|^Description: (.+)$|\1|p' "$template"
			;;
		"default")
			sed -n -r 's|^Default: (.+)$|\1|p' "$template"
			;;
		"description")
			local description=$(grep -e "^\s" "$template" | xargs echo | sed -n -r "s| \. |\n|p")
			echo "$description"
			;;
		"choices")
			IFS=',' read -a choices <<< "$(sed -n -r 's|^Choices: (.+)$|\1|p' "$template" | sed -n -r 's|, ?|,|pg')"
			IFS=',' read -a translations <<< "$(sed -n -r 's|^Translations: (.+)$|\1|p' "$template" | sed -n -r 's|, ?|,|pg')"

			local result=""
			for ((i=0 ; i < ${#choices[@]}; i++)) ; do
				local i18n=$(if [ -z "${translations[$i]}" ]; then echo "${choices[$i]}" ; else echo "${translations[$i]}" ; fi)
				result="${result} \"${choices[$i]}\" \"${i18n}\""
			done
			echo $result
			;;
		*)
			echo ""
			;;
	esac
}

# Puts a question on the buffer of questions to be asked.
wiz_put() {
	wiz_debug "wiz_put"
	local key="$1"
	local unseen_without_key="${WIZ_UNSEEN[@]//$(echo -n "$key")/}"
	hput WIZ_STATES_QUESTIONS "$STATE" "$(hget WIZ_STATES_QUESTIONS "$STATE") $key"

	if [ "$WIZ_RECONFIGURE" = "yes" ] ; then
		# always put dialog if WIZ_RECONFIGURE is set
		WIZ_BUFFER="$WIZ_BUFFER $key"
	elif ! wiz_get "$key" &>/dev/null ; then
		# always put dialog if no existing value
		WIZ_BUFFER="$WIZ_BUFFER $key"
	elif [ ! "$WIZ_UNSEEN" = "$unseen_without_key" ] ; then
		# question has been specifically marked as unseen, to be displayed again
		WIZ_BUFFER="$WIZ_BUFFER $key"
	fi
}

# Sets the question as unseen, meaning it will be displayed event it has already been answered.
wiz_unseen() {
	local key="$1"
	WIZ_UNSEEN="$WIZ_UNSEEN ${key}"
}

# Fetch the value currently stored for a property.
# Returns 0 if a value exists (including empty string), and outputs it on STDOUT.
# Returns 1 if no value has been registered yet.
wiz_get() {
	local key="$1"
	wiz_debug "wiz_get $key"
	if grep -e "^$key " "$DATABASE" &>/dev/null ; then
		sed -n -r "s|^$key (.+)$|\1|p" "$DATABASE"
	else
		return 1
	fi
}

wiz_install_deb() {
	local package="$1"
	apt-get install "$package" -y --force-yes -qq
}

wiz_install_rpm() {
	local package="$1"
	yum install -y -q "$package"
}

wiz_install() {
	local what="$1"

	# return early if command already exists
	if which "$what" &>/dev/null ; then
		return 0
	fi

	case $(wiz_fact "osfamily") in
		"debian")
			wiz_install_deb "$what" ;;
		"redhat")
			wiz_install_debb "$what" ;;
		*)
			echo "Don't know how to install $what on this distribution" ;;
	esac
}

wiz_check_package() {
	case $(wiz_fact "osfamily") in
		"debian")
			dpkg -s "$1" &>/dev/null
			;;
		"redhat"|"suse")
			rpm -qa "$1" | grep -q "$1"
			;;
		*)
			return 1
			;;
	esac
}

# Returns facts about the underlying OS.
# e.g.:
#
# 	wiz_fact "osfamily"
wiz_fact() {
	local key="$1"
	case "$key" in
		"osfamily")
			if [ -f /etc/debian_version ]; then
				echo "debian"
			elif [ -f /etc/SuSE-release ]; then
				echo "suse"
			elif [ -f /etc/redhat-release ]; then
				echo "redhat"
			fi
			;;
		"osversion")
			( . /etc/os-release ; printf '%s' "$VERSION_ID" )
			;;

	esac
}

wiz_join() {
	local IFS="$1"; shift; echo "$*";
}

wiz_urlencode() {
	# urlencode <string>
	local length="${#1}"
	for (( i = 0; i < length; i++ )); do
		local c="${1:i:1}"
		case $c in
			[a-zA-Z0-9.~_-]) printf "$c" ;;
			*) printf '%%%02X' "'$c"
		esac
	done
}

wiz_urldecode() {
	# urldecode <string>
	local url_encoded="${1//+/ }"
	printf '%b' "${url_encoded//%/\x}"
}
