#!/bin/bash

# Licensed under the terms of the Blue Oak Model License 1.0.0
# https://blueoakcouncil.org/license/1.0.0

# The HTML generated assumes the whole site lives in the domain root. This script converts all links
# and image sources to relative URLs, so things don't break when accessed from within a subfolder of
# a live web server. (See ‘publish’ target of makefile)

# Stop on any error, forbid uninitialized vars
set -eu

# First parameter is used as working dir, defaults to ./
base_dir=${1:-"./"}

# Ensure directory name ends with a slash
[[ "${base_dir}" != */ ]] && base_dir="${base_dir}/"

# Ensure directory exists
if [[ ! -d "${base_dir}" ]]; then
    echo "[$(date +'%Y-%m-%dT%H:%M:%S%z')]: ${base_dir} not a directory!" >&2
    exit 1
fi

# Root folder: remove leading / from href and src attributes
sed -i '' -- 's/href=\"\//href=\"/g' "${base_dir}"*.html
sed -i '' -- 's/src=\"\//src=\"/g' "${base_dir}"*.html

# subfolders: replace leading / with ../ in href and src attributes
sed -i '' -- 's/href=\"\//href=\"..\//g' "${base_dir}"articles/*.html
sed -i '' -- 's/src=\"\//src=\"..\//g' "${base_dir}"articles/*.html
sed -i '' -- 's/href=\"\//href=\"..\//g' "${base_dir}"series/*.html
sed -i '' -- 's/src=\"\//src=\"..\//g' "${base_dir}"series/*.html
