#!/bin/bash

set +e    # soft fail to allow handling of php interpreter missing

which php >/dev/null 2>&1
if [ $? -eq 0 ]; then
	php -r 'exit((int) version_compare(PHP_VERSION, "5.4", "<"));' >/dev/null 2>&1
	if [ $? -gt 0 ]; then
		echo "!!! Ushahidi Platform requires PHP 5.4 or newer, please upgrade!"
		exit 1
	fi
fi

set -e    # hard fail to ensure the script exits with non-zero status when something fails

# Defaults
production=false
withgit=false
installdeps=true
migrate=true
nointeraction=false

# Parse options
# Based on code from http://mywiki.wooledge.org/ComplexOptionParsing
optspec=":h-:"
while getopts "$optspec" opt; do
while true; do
	case "${opt}" in
		-) #OPTARG is name-of-long-option or name-of-long-option=value
			if [[ "${OPTARG}" =~ .*=.* ]] #with this --key=value format only one argument is possible
			then
				opt=${OPTARG/=*/}
				OPTARG=${OPTARG#*=}
			else #with this --key value1 value2 format multiple arguments are possible
				opt="$OPTARG"
			fi
			continue #now that opt/OPTARG are set we can process them as if getopts would've given us long options
			;;
		git-update)
			withgit=true
				;;
		production)
			production=true
				;;
		no-deps)
			installdeps=false
				;;
		no-migrate)
			migrate=false
				;;
		no-interaction)
			nointeraction=true
				;;
		h|help)
			echo "usage: $0 [--git-update] [--production] [--no-migrate] [--no-deps] [--no-interaction]" >&2
			exit 2
			;;
	esac
break; done
done

# Deployment mode, disable all developer dependencies :)
if [ -n "$1" -a "$1" == "deploy" ]; then
	production=true
fi

if [ "$withgit" = true ]; then
	echo ">>> Pulling source code"
	git pull
else
	echo ">>> Skipping git"
fi

composer="composer"
phinx="$(dirname "$0")/phinx"

# Check required commands are available
# Have to do this before any modifiers are added to commands
which $composer >/dev/null 2>&1
if [ $? -gt 0 ]; then
	composer="./composer.phar"
	if [ ! -f $composer ]; then
		echo "!!! Missing the 'composer' command, please install it: https://getcomposer.org/"
		exit 1
	fi
fi

# Disable interactive questions
if [ "$nointeraction" = true ]; then
	echo ">>> Disable interactive questions"
	composer="$composer --no-interaction"
fi

# Deployment mode, disable all developer dependencies :)
if [ "$production" = true ]; then
	echo ">>> Skipping development dependencies"
	composer="$composer --no-dev"
fi

if [ "$installdeps" = true ]; then
	echo ">>> Updating dependencies"
	$composer install
else
	echo ">>> Skipping installing all dependencies"
fi

if [ "$migrate" = true ]; then
	# Check phinx
	if [ ! -f "$phinx" ]; then
		echo "!!! Migration tool phinx not installed, unable to run migrations"
		exit 1
	fi
	# Disable interactive questions
	if [ "$nointeraction" = true ]; then
		phinx="$phinx --no-interaction"
	fi
	echo ">>> Running migrations"
	$phinx migrate -c application/phinx.php
else
	echo ">>> Skipping running migrations"
fi
