#!/bin/bash


# TODO
# override apache user with command line option
# override env in command line option
# create holding index.html page
# option to delete holding page
# update database from server
# add sublime project file


SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
DIR=$(pwd)

# default variables
CORE_DIR=core
LOG_DIR=/www/logs
DB_ADMIN_USER=root
read -p "DB Admin Password: " DB_ADMIN_PASS
DB_ADMIN_PASS=${DB_ADMIN_PASS:-tmtRoot99}
DB_HOST=localhost
ENV=dev
PLUGINS=()
CUSTOM_PLUGINS=()
CUSTOM_THEMES=()

PROD_IP=192.168.100.145
DEV_IP=127.0.0.1
STAGE_IP=127.0.0.1
ADDITIONAL_SITE_DOMAINS=()
DEV_SITE_URL=''
STAGE_SITE_URL=''

# check config file
if [ ! -f site.cfg ]; then
	echo -e "\nNo config file found\n"
	exit 1
fi

# bring in config file
source site.cfg


# DYNAMIC VARS
HOST=$(sed -E -e 's_.*://([^/@]*@)?([^/:]+).*_\2_' <<< "$SITE_URL")
DEV_HOST=$(sed -E -e 's_.*://([^/@]*@)?([^/:]+).*_\2_' <<< "$DEV_SITE_URL")
STAGE_HOST=$(sed -E -e 's_.*://([^/@]*@)?([^/:]+).*_\2_' <<< "$STAGE_SITE_URL")
# we're assuming directory structure is /www/vhtdocs/brand/project
PROJECT_NAME=${PWD##*/}
cd ..
BRAND_NAME=${PWD##*/}
cd $PROJECT_NAME
SHORT_DIR=/www/vhtdocs/${BRAND_NAME}/${PROJECT_NAME}
WEB_DIR=${SHORT_DIR}/public
SSL_DIR=${SHORT_DIR}/keys/ssl


## FUNCTIONS

# $1 - db user
# $2 - db pass
# $3 - db host
# $4 - content url
create_config() {

	# we assume we're already in the wp core directory

	# does the config already exist?
	if [ -f wp-config.php ] || [ -f ../wp-config.php ]; then
echo "wp-config already exists"
		# create the wp-config.php file
		wp config create --force --dbname=$DB_NAME --dbuser=$1 --dbpass=$2 --dbhost=$3 --extra-php <<PHP
define( 'WP_CONTENT_DIR', dirname( __FILE__ ) . '/custom' );
define( 'WP_CONTENT_URL', '$4' );
PHP

	else

		wp core config --dbname=$DB_NAME --dbuser=$1 --dbpass=$2 --dbhost=$3 --extra-php <<PHP
define( 'WP_CONTENT_DIR', dirname( __FILE__ ) . '/custom' );
define( 'WP_CONTENT_URL', '$4' );
PHP

	fi

	# move config out to public
	if [ -f wp-config.php ]; then
		mv -f "wp-config.php" ../wp-config.php
	fi
}

# $1 - force copy the theme, string no|yes
copy_custom_themes() {

	# we assume we're already in the site root

	# move them from the GRV tools directory
	for i in "${CUSTOM_THEMES[@]}"
	do
		
		if [ -d ${SCRIPT_DIR}/../src/wordpress/themes/${i} ]; then

			if [ "$1" != "yes" ] && [ -d public/custom/themes/${i} ]; then

				# add overwrite option here?
				echo "Custom theme $i already exists in location"

			else

				if [ -d public/custom/themes/${i} ]; then
					echo "Updating custom theme $i"
					# so delete the old files
					rm -rf public/custom/themes/${i}
				else
					echo "Copying custom theme $i"
				fi

				# here's the copy
				cp -r ${SCRIPT_DIR}/../src/wordpress/themes/${i} public/custom/themes/${i}

			fi

		else
			echo "Custom theme $i not found"
		fi

	done
}

# $1 - to env
switch_env() {

	# we assume we're already in the wp core directory

	# can be prod, dev or stage?
	if [ "$1" == "prod" ]; then 

		echo "to production"

		# change wp dbase options (siteurl & home)
		wp option update siteurl $SITE_URL/$CORE_DIR
		wp option update home $SITE_URL
		# change WP_CONTENT_URL in wp_config
		create_config $DB_USER $DB_PASS $DB_HOST $SITE_URL/custom


	elif [ "$1" == "dev" ]; then 

		echo "to development"

		# change wp dbase options (siteurl & home)
		wp option update siteurl $DEV_SITE_URL/$CORE_DIR
		wp option update home $DEV_SITE_URL
		# change WP_CONTENT_URL in wp_config
		create_config $DB_USER $DB_PASS $DB_HOST $DEV_SITE_URL/custom

	elif [ "$1" == "stage" ]; then 

		echo "to staging"

		# change wp dbase options (siteurl & home)
		wp option update siteurl $STAGE_SITE_URL/$CORE_DIR
		wp option update home $STAGE_SITE_URL
		# change WP_CONTENT_URL in wp_config
		create_config $DB_USER $DB_PASS $DB_HOST $DEV_SITE_URL/custom

	else 
		echo -e "\nNot a valid environment"
		exit 1
	fi
}



# JOBS

# BUILD
if [ "$1" == "build" ]; then 
    
	echo -e "\nBUILDING"
	echo "========"


	# write out git.ignore
	echo -e "\nGIT IGNORE"

	if [ -f .gitignore ]; then
		echo "Git ignore exists"
	else

		echo "Creating git ignore"

		/bin/cat <<EOM >.gitignore
node_modules
vendor
public/core/*
public/static/uploads/*
public/custom/plugins/*
!amp-theme-framework-master
public/custom/upgrade/*
public/custom/themes/*
!*-child
wp-config.php
EOM

fi

	
	## CHECK COMPOSER

	echo -e "\nCHECKING COMPOSER"

	# Create the composer if not exists
	# post-install used to do this:
	# "[[ -f /usr/local/bin/wp ]] || sudo ln -fs $DIR/vendor/wp-cli/wp-cli/bin/wp /usr/local/bin/wp",
	# but that stopped wp-cli updating
	if [ -f composer.json ]; then
		echo "composer.json exists"
	else

		echo "creating composer.json"

	    /bin/cat <<EOM >composer.json
{
    "require": {
        "wp-cli/wp-cli" : "~1.4",
        "psy/psysh" : "~0.6",
        "phpmailer/phpmailer": "^6.0"
    },
    "scripts" : {
        "post-install-cmd" : [
            "sudo ln -fs $SHORT_DIR/vendor/wp-cli/wp-cli/bin/wp /usr/local/bin/wp",
            "source $SHORT_DIR/vendor/wp-cli/wp-cli/utils/wp-completion.bash",
            "[[ -f ~/.bash_profile ]] || touch ~/.bash_profile",
            "source ~/.bash_profile"
        ],
        "post-update-cmd" : [
            "sudo ln -fs $SHORT_DIR/vendor/wp-cli/wp-cli/bin/wp /usr/local/bin/wp",
            "source $SHORT_DIR/vendor/wp-cli/wp-cli/utils/wp-completion.bash",
            "[[ -f ~/.bash_profile ]] || touch ~/.bash_profile",
            "source ~/.bash_profile"
        ]
    }
}
EOM

	fi

	# install composer
	echo "installing composer modules"
	composer install



	## WP DOWNLOAD

	echo -e "\nWP DOWNLOAD"

	if [ -d public/$CORE_DIR ]; then
		echo "WP install exists"
	else

		echo "Downloading WP"

		# create the dir for the core files
		mkdir -p public/$CORE_DIR
		cd public/$CORE_DIR

		# download WordPress files
		wp core download

		# move back out to root
		cd ../../

	fi



	## CREATE DIRECTORIES

	echo -e "\nCHECKING DIRECTORIES"

	cd public

	# make the custom directories
	if [ ! -d custom ]; then
		echo "Creating custom directories"
		mkdir -p custom/plugins
		mkdir -p custom/themes
		mkdir -p custom/upgrade
	fi

	# create uploads directory and set ownership to apache
	if [ ! -d static ]; then
		echo "Creating static directory"
		mkdir -p static/uploads
		sudo chown -R _www:_www static/uploads
	fi

	# create log directory and set ownership to apache
	if [ ! -d ${LOG_DIR}/${BRAND_NAME} ]; then
		echo "Creating log directory"
		mkdir -p ${LOG_DIR}/${BRAND_NAME}
		sudo chown -R _www:_www ${LOG_DIR}/${BRAND_NAME}
	fi

		# make sure group is not writeable on parent directory to avoid logrotate permissions errors
		# parent directory has insecure permissions (It's world writable or writable by group which is not "root")
		sudo chmod 755 ${LOG_DIR}/${BRAND_NAME}

	# move back out to root
	cd ../



	## CUSTOM THEMES

	echo -e "\nCOPYING CUSTOM THEMES"

	copy_custom_themes



	## CUSTOM PLUGINS

	echo -e "\nCOPYING CUSTOM PLUGINS"

	# move them from the GRV tools directory
	for i in "${CUSTOM_PLUGINS[@]}"
	do
		
		if [ -d ${SCRIPT_DIR}/../src/wordpress/plugins/${i} ]; then

			if [ -d public/custom/plugins/${i} ]; then

				# add overwrite option here?
				echo "Custom plugin $i already exists in location"

			else

				echo "Copying custom plugin $i"
				cp -r ${SCRIPT_DIR}/../src/wordpress/plugins/${i} public/custom/plugins/${i}

			fi

		else
			echo "Custom plugin $i not found"
		fi

	done



	## CONFIG
	# this puts the config in public we may want to consider whether we can move it outside of public

	echo -e "\nWP CONFIG"

	if [ -f public/wp-config.php ]; then
		echo "WP config exists"
	else

		echo "Creating config file"

		# move in to public core
		cd public/$CORE_DIR

		# create the wp-config.php file
		create_config $DB_ADMIN_USER $DB_ADMIN_PASS $DB_HOST $SITE_URL/custom

		# move back out to root
		cd ../../

	fi



	## DATABASE

	echo -e "\nDATABASE"

	RESULT=`mysql -u$DB_ADMIN_USER -p$DB_ADMIN_PASS -e "SHOW DATABASES" | grep -e ^$DB_NAME$`
	if [ "$RESULT" == "$DB_NAME" ]; then
		echo "WP and database already installed"
	else
		
		echo "Creating database"

		# move in to public core
		cd public/$CORE_DIR

		# we need an admin config
		create_config $DB_ADMIN_USER $DB_ADMIN_PASS $DB_HOST $SITE_URL/custom

		# create the database
		wp db create

		# create mysql user with permissions on the db
		mysql -u$DB_ADMIN_USER -p$DB_ADMIN_PASS -e "CREATE USER ${DB_USER}@localhost IDENTIFIED BY '${DB_PASS}';"
	    mysql -u$DB_ADMIN_USER -p$DB_ADMIN_PASS -e "GRANT ALL PRIVILEGES ON ${DB_NAME}.* TO '${DB_USER}'@'localhost';"
	    mysql -u$DB_ADMIN_USER -p$DB_ADMIN_PASS -e "FLUSH PRIVILEGES;"

		# switch config to use site username and pass
		# create the wp-config.php file
		create_config $DB_USER $DB_PASS $DB_HOST $SITE_URL/custom

		# move back out to root
		cd ../../



		## WP INSTALL
		# we've had to move this in to the database check as $(wp core is-installed) was not working as an install check
		# so now, no database means not installed

		echo -e "\nWP INSTALL"

		# move to core dir
		cd public/$CORE_DIR

	#if [ ! $(wp core is-installed)]; then

		echo "Installing WP"

	    # install WordPress (less than 5 mins)
		wp core install --url=$SITE_URL --title="$SITE_TITLE" --admin_user=$SITE_USER --admin_password=$SITE_PASS --admin_email=$SITE_EMAIL

		# move in to public
		cd ../

		if [ ! -f index.php ]; then

			echo "Creating index page"

			# Copy (not move) index.php file to root
			cp "$CORE_DIR/index.php" index.php

			# Edit index.php to point to correct path of wp-blog-header.php
			# don't need this as the index is version controlled
			sed -i '' "s/\/wp-blog-header/\/$CORE_DIR\/wp-blog-header/g" index.php

		fi

		# to core dir
		cd $CORE_DIR

		# Update the siteurl in the database with sub directory path
		wp option update siteurl $SITE_URL/$CORE_DIR

		# update upload dirs
		wp option update upload_path ../static/uploads
		wp option update upload_url_path /static/uploads

		# cleanups only to be done on install
		echo "Clearing out default posts (hello world)"
		wp post delete $(wp post list --post_type='post' --format=ids)
		#wp post delete $(wp post list --post_type='page' --format=ids)

		echo "Clearing out default comments"
		wp comment delete $(wp comment list --number=### --status=spam --field=ID)

		# creation only to be done on install
		echo "Creating core pages (contact us, about us)"
		wp post create --post_type=page --post_status=publish --post_title='Privacy'
		wp post create --post_type=page --post_status=publish --post_title='About'
		wp post create --post_type=page --post_status=publish --post_title='Contact'

		echo "Setting permalink structure for posts ('news/name-of-article-etc')"
		wp rewrite structure '/news/%postname%/' --hard
		wp rewrite flush --hard

		# users should be in the seed file
		if [ -f ../../seed.xml ]; then
			echo "Seeding data"
			wp import ../../seed.xml --authors=create
		fi

		# post-install script
		if [ -f ../../post-install ]; then
			echo "Running post install script"
			source ../../post-install
		fi

		cd ../../
		
	fi



	## ACTIVATE THE THEME

	if [ ! -z "$var" ]; then

		echo -e "\nACTIVATING THEME"

		cd public/$CORE_DIR

		# check the child theme exists and create if not
		if [ ! -d ../custom/themes/${SITE_THEME_NAME}-child ]; then

			echo "Creating child theme for ${SITE_THEME_NAME}"

			wp scaffold child-theme ${SITE_THEME_NAME}-child --parent_theme=${SITE_THEME_NAME}

		fi

		wp theme activate ${SITE_THEME_NAME}-child

		cd ../../

	fi



	## STANDARD PLUGINS

	echo -e "\nSTANDARD PLUGINS"

	cd public/$CORE_DIR

	for i in "${PLUGINS[@]}"
	do
		echo "Installing $i"
		wp plugin install $i --activate
	done

	cd ../../



	## ACTIVATE CUSTOM PLUGINS

	echo -e "\nACTIVATE CUSTOM PLUGINS"

	cd public/$CORE_DIR

	for i in "${CUSTOM_PLUGINS[@]}"
	do
		echo "Activating $i"
		wp plugin activate $i
	done

	cd ../../



	## CREATE SELF SIGNED SSL CERTS

	echo -e "\nCHECKING SSL CERTS"

	# create this folder and add certs in if we have proper certs for the site
	if [ ! -d keys/ssl ]; then

		echo "Creating certs"

		mkdir -p keys/ssl

		cd keys/ssl

		sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout ${HOST}.key -out ${HOST}.key.crt

		cd ../..

	else
		echo "Certs exist"
	fi



	## VHOSTS

	echo -e "\nCHECKING VHOSTS"
	
	if [ ! -d vhosts ]; then

		echo "Creating vhost directory"

		mkdir -p vhosts
	fi

	if [ ! -f vhosts/${BRAND_NAME}.conf ]; then

		echo "Creating vhost conf file"

		cp ${SCRIPT_DIR}/../src/wordpress/vhost/template.conf vhosts/${BRAND_NAME}.conf

		# replacements
		
		# ##IP_ADDRESSES##
		IP_STRING=${PROD_IP}:443
		if [ $PROD_IP != $DEV_IP ];then
			IP_STRING="${IP_STRING} ${DEV_IP}:443"
		fi
		if [ $PROD_IP != $STAGE_IP ] && [ $STAGE_IP != $DEV_IP ];then
			IP_STRING="${IP_STRING} ${STAGE_IP}:443"
		fi
		sed -i -e "s%##IP_ADDRESSES##%$IP_STRING%g" vhosts/${BRAND_NAME}.conf
		
		# ##SITE_TITLE##
		sed -i -e "s%##SITE_TITLE##%$SITE_TITLE%g" vhosts/${BRAND_NAME}.conf
		
		# ##SSL_CERT##
		SSL_CERT=${SSL_DIR}/${HOST}.key.crt
		sed -i -e "s%##SSL_CERT##%$SSL_CERT%g" vhosts/${BRAND_NAME}.conf
		
		# ##SSL_KEY##
		SSL_KEY=${SSL_DIR}/${HOST}.key
		sed -i -e "s%##SSL_KEY##%$SSL_KEY%g" vhosts/${BRAND_NAME}.conf
		
		# ##DOCUMENT_ROOT##
		sed -i -e "s%##DOCUMENT_ROOT##%$WEB_DIR%g" vhosts/${BRAND_NAME}.conf
		
		# ##LOG_DIR##
		FULL_LOG=${LOG_DIR}/${BRAND_NAME}
		sed -i -e "s%##LOG_DIR##%$FULL_LOG%g" vhosts/${BRAND_NAME}.conf
		
		# ##HOST##
		sed -i -e "s%##HOST##%$HOST%g" vhosts/${BRAND_NAME}.conf
		
		# ##SITE_URL##
		sed -i -e "s%##SITE_URL##%$SITE_URL%g" vhosts/${BRAND_NAME}.conf
		
		# ##HOST_ALIASES##
		ALT_HOSTS=()
		if [ ${HOST/www./} != $HOST ]; then
			ALT_HOSTS+=(${HOST/www./})
		fi
		if [ ${#DEV_HOST} -gt 0 ]; then 
			ALT_HOSTS+=(${DEV_HOST})
			if [ ${DEV_HOST/www./} != $DEV_HOST ]; then
				ALT_HOSTS+=(${DEV_HOST/www./})
			fi
		fi
		if [ ${#STAGE_HOST} -gt 0 ]; then 
			ALT_HOSTS+=(${STAGE_HOST})
			if [ ${STAGE_HOST/www./} != $STAGE_HOST ]; then
				ALT_HOSTS+=(${STAGE_HOST/www./})
			fi
		fi
		for i in "${ADDITIONAL_SITE_DOMAINS[@]}"
		do
			ALT_HOSTS+=($i)
			if [ ${i/www./} != $i ]; then
				ALT_HOSTS+=(${i/www./})
			fi
		done
		HOST_ALIASES=$(IFS=" " ; echo "${ALT_HOSTS[*]}")
		sed -i -e "s%##HOST_ALIASES##%$HOST_ALIASES%g" vhosts/${BRAND_NAME}.conf
		
		# ##REDIRECT_HOSTS##
		REDIRECT_HOST_ARR=()
		for i in "${ALT_HOSTS[@]}"
		do
			if [ "$i" != "$HOST" ] && [ "$i" != "$DEV_HOST" ] && [ "$i" != "$STAGE_HOST" ]; then
				REDIRECT_HOST_ARR+=($i)
			fi
		done
		REDIRECT_HOSTS=$(IFS="|" ; echo "${REDIRECT_HOST_ARR[*]}")
		REDIRECT_HOSTS="^(${REDIRECT_HOSTS})$"
		sed -i -e "s%##REDIRECT_HOSTS##%$REDIRECT_HOSTS%g" vhosts/${BRAND_NAME}.conf

		# delete the backup file
		rm vhosts/${BRAND_NAME}.conf-e

	fi


	## SWITCH ENV

	cd public/$CORE_DIR
	switch_env $ENV
	cd ../../


	echo -e '\nBuild finished!'


# SWITCH ENV
elif [ "$1" == "env" ]; then 

	echo -e "\nSETTING ENVIRONMENT"

	cd public/$CORE_DIR

	switch_env $2

	cd ../../


# SWITCH ENV
elif [ "$1" == "update_custom_themes" ]; then 

	echo -e "\nUPDATING CUSTOM THEMES"

	copy_custom_themes yes


else
    echo -e "\nOption not valid\n"
    exit 1
fi

echo -e "\n"
