#!/bin/bash
FOLDER="step2education.com"
TARGET_DIR="/var/www"
GIT_DIR="/var/www/git/step2web"
BRANCH="main"
timestamp=$(date +%s)

# create temp directory
mkdir "${TARGET_DIR}/${FOLDER}.new" || die "can't create work dir ${TARGET_DIR}/${FOLDER}.new"

while read oldrev newrev ref
do
	# only checking out the master (or whatever branch you would like to deploy)
	if [ "$ref" = "refs/heads/$BRANCH" ];
	then
		echo "Ref $ref received. Deploying ${BRANCH} branch to production..."
		git --work-tree="${TARGET_DIR}/${FOLDER}.new" --git-dir=$GIT_DIR checkout -f $BRANCH
		#find $TARGET -type f -exec chmod 664 -R {} \;
		#find $TARGET -type d -exec chmod 775 -R {} \;
	else
		echo "Ref $ref received. Doing nothing: only the ${BRANCH} branch may be deployed on this server."
	fi
done

# add symlink to logs
ln -ds "${TARGET_DIR}/log" "${TARGET_DIR}/${FOLDER}.new/logs"
cp -a "${TARGET_DIR}/${FOLDER}/configuration.php" "${TARGET_DIR}/${FOLDER}.new/configuration.php" 
mv "${TARGET_DIR}/${FOLDER}" "${TARGET_DIR}/${FOLDER}.${timestamp}" && mv "${TARGET_DIR}/${FOLDER}.new" "${TARGET_DIR}/${FOLDER}"
