#!/usr/bin/env bash

if [ "$1" == "debug" ]; then
	set -x
	shift
fi

if [[ ! -z $(which tput) ]]; then
	normal=$(tput sgr0)
	bold=$(tput bold)
	red=$(tput setaf 1)
	green=$(tput setaf 2)
	yellow=$(tput setaf 3)
	magenta=$(tput setaf 5)
fi


# Usage: info "message"
# Example: info "doing thing"
# Output (to STDOUT): doing thing
info() {
	printf "%b" "${bold}${yellow}$1${normal} \n"
}

# Usage: success "message"
# Example: success "It's Working"
# Output (to STDOUT): [...] It's Working
success() {
	printf "%b" "[${green}Success${normal}]${green} $1 ${normal}\n"
}

# Usage: warning "message"
# Example: warning "some warning"
# Output (to STDOUT): [...] some warning
warning() {
	printf "%b" "${red} $1 ${normal}\n"
}

# Usage: prompt "question"
# Example: prompt "Site name"
# Output (to STDOUT): Site Name:
prompt() {
	printf "%b" "${magenta} $1: ${normal}"
}

# Usage: error ["message"]
# Example: error "this is an error"
# Output (to STDERR): [ERROR] this is an error
error() {
    printf "%b" "[${bold}${red}Error${normal}]${bold}${red} ${1:-'Unknown Error'}${normal}\n" >&2
}

# Usage: fail "message"
# Example: fail "Unknown Option" 254
fail() {
	error "$1"
	exit 1
}

argument_expected() {
    if [ -z "$2" ] || [[ "$2" == -* ]]; then
        fail "$1 expected an argument"
    fi
}

check_for_path() {

	test -f "$HOME"/.vvv-flipper && got_config="true"

	if [ ! -z $got_config ]; then
		path=$(cat "$HOME"/.vvv-flipper)
	else
		current_dir=$(pwd)
		if [ -e "$current_dir/Vagrantfile" ]; then
			path=$(pwd)
		elif [ -e "$HOME"/Sites/Vagrantfile ]; then
			path="$HOME"/Sites
		elif [ -e "$HOME"/Sites/Vagrant/Vagrantfile ]; then
			path="$HOME"/Sites/Vagrant
		elif [ -e "$HOME"/vagrant/Vagrantfile ]; then
			path="$HOME"/vagrant
		elif [ -e "$HOME"/vagrant-local/Vagrantfile ]; then
			path="$HOME"/vagrant-local
		elif [ -e "$HOME"/projects/vvv/Vagrantfile ]; then
			path="$HOME"/projects/vvv
		elif [ -e "$HOME"/working/vvv/Vagrantfile ]; then
			path="$HOME"/working/vvv
		elif [ -e "$HOME"/vvv/Vagrantfile ]; then
			path="$HOME"/vvv
		fi
		info "Automagically found $path"
		prompt "Is this where VVV is installed? (Y/n)"
		read -r path_confirmation
		if [ "$path_confirmation" = 'n' ]; then
			unset path
		fi

		while [ -z "$path" ]; do
			read -r -e -p "VVV install directory: " path

			# Make sure directory is actually a VVV root
			if [ ! -e "$(eval echo "${path//>}")/Vagrantfile" ]; then
				error "Path specified is not a VVV root directory. Where is VVV installed?"
				unset path
			fi
			path=$(eval echo "${path//>}")
		done

		path=${path%/}

		echo "$path" > "$HOME"/.vvv-flipper
	fi
}

check_for_provision_scripts_folder() {
	check_for_path
	test -d "$path/provision/scripts" && got_scripts_config="true"

	if [ -z "$got_scripts_config" ]; then
		info "Creating folder for scripts folder: $path/provision/scripts..."
		mkdir -p "$path/provision/scripts"
		success "Done"

		if [ ! -z "$(which curl)" ]; then
			info "Downloading sample provision script..."
			curl --silent https://raw.githubusercontent.com/bradp/vvv-provision-flipper/master/scripts/sample > "$path/provision/scripts/quick"
			cp "$path/provision/provision.sh" "$path/provision/scripts/sample"
			success "Done"
		else
			error "Could not download sample provision script."
		fi

		test -f "$path"/provision/provision-custom.sh && custom_provision="true"

		if [ ! -z "$custom_provision" ]; then
			mv "$path"/provision/provision-custom.sh "$path"/provision/scripts/original
			info "Moved your current custom script to $path/provision/scripts/original"
			set_custom "original"
		fi

	fi
}

remove_custom_provisioning_script() {
	check_for_path
	check_for_provision_scripts_folder
	test -f "$path"/provision/provision-custom.sh && custom_provision="true"
	if [ ! -z "$custom_provision" ]; then
		mv "$path"/provision/provision-custom.sh "$path"/provision/scripts/backup
		success "Removed custom provision script. Stored a backup in $path/provision/scripts/backup"
	fi
}

set_custom() {
	check_for_path
	check_for_provision_scripts_folder
	test -f "$path"/provision/scripts/"$1" && script_exists="true"
	if [ ! -z "$script_exists" ]; then
		remove_custom_provisioning_script
		cp "$path"/provision/scripts/"$1" "$path"/provision/provision-custom.sh
		success "Set up $1 as the custom provision script."
	else
		error "A script of that name was not found in $path/provision/scripts."
	fi
}

run_vagrant_provision() {
	check_for_path
	cd "$path"
	info "Attempting to run 'vagrant provision' in $path "
	provision_results="$(vagrant provision)"

	if [[ "$provision_results" == *"VM is not currently running"* ]]; then
		info "Running 'vagrant up' and 'vagrant provision'"
	  vagrant up --provision
	fi

	success "vagrant provision complete"
}


check_args() {
	while [ ! -z "$1" ]; do
		case "$1" in
			full|reset)
				remove_custom_provisioning_script
				shift
				;;
			set)
				argument_expected "$1" "$2"
				set_custom "$2"
				shift 2
				;;
			use)
				argument_expected "$1" "$2"

				set_custom "$2"
				run_vagrant_provision
				set_custom "backup"
				shift 2
				;;
			provision)
				run_vagrant_provision
				exit
				;;
			*)
				fail "Unknown option $1"
				shift
				;;
		esac
	done
	exit 0
}

main() {
	if [ -z "$1" ]; then
	    check_for_path
	    check_for_provision_scripts_folder
	fi
	check_args "$@"
}
main "$@"