#!/bin/bash

# Michael McMahon 2022

# Cron bash script to update the JShelter Pelican site.

set -euo pipefail

# date +%s >> /tmp/diditrun.txt  # DEBUG

# Check if this script is already running so that it can be run as a cronjob every minute.
SCR_NAME="$(basename "$0")"  # Name of this script.
PID="$(echo $$)"  # Process ID of this script.
if [ $(ps -ef | grep $SCR_NAME | grep -v -e su -e timeout -e grep -e $PID | wc -l) -gt 0 ]; then
  # echo "This is script is already running!"  # DEBUG
  exit
  # Doc: Kill this script if it is running for more than 5 minutes.
  # Run this script with: timeout 5m bash script.sh
  # Cron example:
  # * * * * * webfiles timeout 5m /usr/local/bin/deploy_script.sh
fi

# Verbose
#cd /home/webfiles/webextension/website/
#git fetch && git pull
#make html
#rsync -rvc output/ /var/www/html/

# Quiet

# Change directory.
cd /home/webfiles/webextension/website/

# Fetch and pull updates from repo.
git fetch -q &>/dev/null || git fetch
git pull -q &>/dev/null || git pull

# Run the website portion of the makefile.
# Silence all expected outputs unless exits with 1.
make html &>/dev/null || make html

# Copy all of the contents to the website directory.
rsync -rc output/ /var/www/html/

# TODO If a file in /var/www/html/ is not in output/, remove it.

# DEBUG
date +%s >> /tmp/diditrun.txt
