#!/bin/sh

# You *must* change html_dir and html_file to your own paths:
html_dir=~/html/
html_file='index.html'

# You *can* change tmp_file and backup_name if you want:
tmp_file='.tmp.html'
backup_name=".backup-index.html"

util_name=$(basename "$0")

echo "${util_name}: hi ~${USER}, nice to see you :>"

if ! [ -d "$(realpath $html_dir)" ] ; then
    echo "${util_name}: html_dir '$html_dir' does not exist." >&2 
    exit 1
fi

if ! cd "$html_dir"
then
    echo "${util_name}: failed to cd to '$html_dir'" >&2 
    exit 1
fi
echo " -- changed directory to '$(pwd)'"


if ! [ -f "$html_file" ]; then
    echo "${util_name}: html_file '$html_file' does not exist." >&2 
    exit 1
fi

echo " -- backing up '$html_file' to '$backup_name'..."
cp "$html_file" "$backup_name"

echo " -- updating still-alive-date in '$html_file' and writing to tmpfile '$tmp_file'..."

awk -P -v date="$(date --iso-8601)" 'BEGIN { date_str = "<still-alive>still alive: <em>" date "</em></still-alive>"; } { gsub(/<still-alive.*>[[:space:]]*still.?alive.*<\/still-alive>/, date_str);  print $0; }' "$html_file" > "$tmp_file"

if [ $? -ne 0 ]; then
    echo "${util_name}: html_file '$html_file' does not exist." >&2 
    exit 1
fi

echo " -- moving '$tmp_file' to '$html_file'..."
mv "$tmp_file" "$html_file"

if [ $? -ne 0 ]; then
    echo "${util_name}: failed to move '$tmp_file' to '$html_file'" >&2 
    exit 1
fi

echo "${util_name}: Done! You are still alive :)"

