#!/usr/bin/env bash

# HELPER PURPOSE
#
# Deploy to Github Pages
# Your project should set the GITHUB_EMAIL, GITHUB_NAME and TARGET_DIR variables in Vault

TARGET_BRANCH=gh-pages
TEMP_DIR=tmp

# Set error handling
set -eu -o pipefail

# Set GitHub user information (the email must match the SSH key provided to Circle)
git config --global user.email $GITHUB_EMAIL
git config --global user.name $GITHUB_NAME

# HACK: Add GitHub to known hosts to avoid an interactive prompt when cloning over SSH
mkdir -p ~/.ssh
ssh-keyscan -H github.com >> ~/.ssh/known_hosts

# Clone only the branch we need so we don't download all of the project history
git clone $CIRCLE_REPOSITORY_URL $TEMP_DIR --single-branch --branch $TARGET_BRANCH

# Remove all of the files, -q prevents logging every filename
cd $TEMP_DIR
git rm -rf .
cd ..

# Copy contents of target directory to the deployment directory
cp -R -L $TARGET_DIR $TEMP_DIR

# Copy CI config (which should instruct Circle to ignore this branch)
cp -r .circleci $TEMP_DIR

cd $TEMP_DIR

# Stage and commit all of the files
git add -A &> /dev/null
git commit -m "Automated deployment to GitHub Pages: ${CIRCLE_SHA1}" --allow-empty

# Push to the target branch, staying quiet unless something goes wrong
git push -q origin $TARGET_BRANCH
