#!/usr/bin/env bash

source "${BASH_SOURCE%/*}/resources/functions.sh"

help_message() {
	echo "$(tput setaf 2)turnip - Project installer$(tput sgr0)

USAGE:
turnip [OPTIONS]
    $(tput setaf 2)--repo    (-r)$(tput sgr0)    Theme name
    $(tput setaf 2)--version (-v)$(tput sgr0)    Themes branch or tag, defaults to 'master'
    $(tput setaf 2)--help    (-h)$(tput sgr0)    Shows this message

This script will:
    * Install project repository
    * Build theme using the theme's bin/install-theme.sh script
    * Expose vendor directories
    * Build and flush SilverStripe

Via Composer, you can run this script with 'composer exec turnip -- [OPTIONS]'";
}

CMS_ROOT_DIR="$( pwd )"
INSTALL_THEME_SCRIPT="$CMS_ROOT_DIR/app/bin/install-theme.sh"
REPO=""
VERSION="master"

[ ! -d "vendor" ] && error_msg && echo "Script must be run from the CMS root directory" && error

while [[ "$1" == -* ]]; do
	opt=$1
	shift
	case "$opt" in
		--repo)
			REPO="$1";
			shift ;;
		--version)
			VERSION="$1"
			shift ;;
		--help)
			help_message && exit 0
			;;
		*)
			error_msg && echo >&2 "Unrecognized option $opt." && error
			;;
	esac
done

[ -z "$REPO" ] && error_msg && echo "No repository specified" && error

if [ -d "app" ]; then
	info_msg && echo "app directory exists. Pulling from $VERSION..."
	( cd app && git pull origin "$VERSION" )
else
	info_msg && echo "Cloning app"
	git clone --quiet --branch "$VERSION" "git@bitbucket.org:fastrackgroup/$REPO.git" "app"
fi

if [ -e "$INSTALL_THEME_SCRIPT" ]; then
	info_msg && echo "Building theme"
	"$INSTALL_THEME_SCRIPT"
else
	notice_msg && echo "Theme install script not found"
fi

cd "$CMS_ROOT_DIR" || { error_msg ; echo "Could not cd to $CMS_ROOT_DIR"; error; }

info_msg && echo "Building database"
composer vendor-expose && \
composer exec sake -- "dev/build" "flush=1" && \

info_msg && echo "Installation complete"
