#!/usr/bin/env bash

#: exec_target = cli

## Initialize/reinstall site
##
## Usage: fin init-site

# Abort if anything fails
set -e

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

# PROJECT_ROOT and DOCROOT are set as env variables in cli
SITE_DIRECTORY="default"
DOCROOT_PATH="${PROJECT_ROOT}/${DOCROOT}"
SITEDIR_PATH="${DOCROOT_PATH}/sites/${SITE_DIRECTORY}"

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

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

# Console colors
red='\033[0;31m'
green='\033[0;32m'
green_bg='\033[1;97;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}"; }

# 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 "${dest} already in place."
	fi
}

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

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

composer_install ()
{
	cd "$PROJECT_ROOT"
	echo-green "Installing dependencies..."
	composer install
}

# 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}"
}

# Install site
site_install ()
{
	cd "$DOCROOT_PATH"

	echo-green "Installing Drupal..."
	drush site-install standard -y --site-name='My Drupal 9 Site'
}

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

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

# Project initialization steps
time -p composer_install
fix_permissions
init_settings
time -p site_install

echo -e "Open ${yellow}http://${VIRTUAL_HOST}${NC} in your browser to verify the setup."
echo-yellow "Look for admin login credentials in the output above."

#-------------------------- END: Execution --------------------------------
