#!/usr/bin/env bash

## Initialize a content_translation_access drupal environment
##
## Usage: fin init sitename uri

# Abort if anything fails
set -e

#-------------------------- Settings --------------------------------

# PROJECT_ROOT is passed from fin.
# The following variables are configured in the '.env' file: DOCROOT, VIRTUAL_HOST.

SITE_DIRECTORY="default"
URI="$2"
DOCROOT_PATH="${PROJECT_ROOT}/build"
SITEDIR_PATH="${DOCROOT_PATH}/sites/${SITE_DIRECTORY}"

#-------------------------- END: Settings --------------------------------

#-------------------------- Helper functions --------------------------------

# Console colors
red='\033[0;31m'
green='\033[0;32m'
green_bg='\033[42m'
yellow='\033[1;33m'
NC='\033[0m'

echo-red () { echo -e "${red}$1${NC}"; }
echo-green () { echo -e "${green}$1${NC}"; }
echo-green-bg () { echo -e "${green_bg}$1${NC}"; }
echo-yellow () { echo -e "${yellow}$1${NC}"; }

is_windows ()
{
	local res=$(uname | grep 'CYGWIN_NT')
	if [[ "$res" != "" ]]; then
		return 0
	else
		return 1
	fi
}

# Copy a settings file.
# Skips if the destination file already exists.
# @param $1 source file
# @param $2 destination file
copy_settings_file()
{
	local source="$1"
	local dest="$2"

	if [[ ! -f $dest ]]; then
		echo "Copying ${dest}..."
		cp $source $dest
	else
		echo-yellow "${dest} already in place."
	fi
}

#-------------------------- END: Helper functions --------------------------------

#-------------------------- Functions --------------------------------

# Initialize local settings files
init_settings ()
{
	# Copy from settings templates
	copy_settings_file "${SITEDIR_PATH}/default.settings.local.php" "${SITEDIR_PATH}/settings.local.php"
}

# Fix file/folder permissions
fix_permissions ()
{
	echo-green "Making site directory writable..."
	chmod 755 "${SITEDIR_PATH}"
	chmod 755 "${SITEDIR_PATH}/settings.php"
}

# Install site
composer_install ()
{
	cd ${PROJECT_ROOT}
	fin exec composer install
	fin exec composer drupal-scaffold
}

# Install site
site_install ()
{
	# We disable email sending here so site-install does not return an error
    cd $PROJECT_ROOT
    fin up
    copy_settings_file "${PROJECT_ROOT}/runner.yml.dist" "${PROJECT_ROOT}/runner.yml"
	fin exec run drupal:site-setup
	fin exec run drupal:site-install
}

#-------------------------- END: Functions --------------------------------

#-------------------------- Execution --------------------------------

if [[ "$PROJECT_ROOT" == "" ]]; then
	echo-red "\$PROJECT_ROOT is not set"
	exit 1
fi

# Project initialization steps
#echo -e "${green_bg} Step 1 ${NC}${green} Initializing local project configuration...${NC}"
#fix_permissions
#init_settings

echo -e "${green_bg} Step 2 ${NC}${green} Installing composer...${NC}"
time composer_install

echo -e "${green_bg} Step 3 ${NC}${green} Installing site...${NC}"
sleep 10
time site_install

echo -en "${green_bg} DONE! ${NC} "
echo -e "Open ${yellow}http://${VIRTUAL_HOST}${NC} in your browser to verify the setup."
