#!/usr/bin/env bash

DEPLOY_BRANCH='gh-pages'
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)

# USAGE:
#  deploy.sh [target_branch]

# This script relies on some environment variables and assumptions that are only
# present/valid in Codespaces

GREEN='\033[0;32m'
LIGHT_GREEN='\033[1;32m'
RED='\033[0;31m'
NC='\033[0m' # No Color

if [[ -n "${1}" ]]; then
    TARGET=$1
else
    TARGET=$DEPLOY_BRANCH
fi

function step () {
    printf "${LIGHT_GREEN}  $*  ${NC}\n"
}

function substep () {
    printf "${GREEN}      $*  ${NC}\n"
}

function error () {
    printf "${RED} $* ${NC}\n"
    git checkout ${CURRENT_BRANCH}
    exit 1
}

function working_dir_clean () {
    git diff-index --quiet HEAD
}

step "Making sure we're in a Codespace"
if [ -z "$CODESPACES" ]; then
  error "You must be in a Codespace to deploy"
fi

step "Running the setup script, just in case"
script/setup || error "Setup failed. Check above for errors."

step "Ensuring that the git working directory is clean..."
if working_dir_clean; then
    substep "all changes are committed."
elif [[ -n $ALLOW_DIRTY_DEPLOY ]]; then
    substep "deploying despite dirt."
else
    error "You have uncommitted changes! Please commit, stash, or reset before deploying."
fi

step "Deploying to ${TARGET}:"

substep "Building site..."
stack build && stack exec ppj-blog build || error "Unable to build site! Check above for errors."

substep "Checking out ${TARGET}..."
git checkout ${TARGET} || error "Unable to checkout ${TARGET}! Please make sure that branch exists."

substep "On ${TARGET}. Copying files..."
cp -a _site/. . || error "Unable to copy!"

substep "Committing new contents..."
git add -A && git commit -m "automated deployment $(date)" || error "Unable to commit! Maybe a git config issue?"

substep "Pushing to github pages..."
git pull origin -r || error "Unable to sync with ${TARGET} first."
git push origin HEAD || error "Unable to push! That seems weird."

step "Deployed!"

step "Returning things back to normal."

substep "Checking out previous branch..."
git checkout ${CURRENT_BRANCH} || error "Unable to return to original branch! What kind of nonsense is this?"

step "All done!"
