#!/usr/bin/env bash

set -euo pipefail

DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SITE_DIR="$DIR/pocketpond"
LOCAL_DIR="$DIR/pocketpond-local"
REWRITE_AWK="$DIR/offline-rewrite.awk"

if ! command -v awk >/dev/null 2>&1; then
  echo "awk not found on this system." >&2
  exit 1
fi

echo "Preparing a refactored offline copy in pocketpond-local/ ..."
rm -rf "$LOCAL_DIR"
cp -R "$SITE_DIR" "$LOCAL_DIR"

while IFS= read -r -d '' file; do
  rel="${file#"$LOCAL_DIR"/}"
  slashes="${rel//[^\/]/}"
  depth=${#slashes}

  prefix=""
  for ((i = 0; i < depth; i++)); do
    prefix="../$prefix"
  done

  tmp="$file.tmp"
  awk -v prefix="$prefix" -f "$REWRITE_AWK" "$file" > "$tmp"
  mv "$tmp" "$file"
done < <(find "$LOCAL_DIR" -name '*.html' -print0)

INDEX="$LOCAL_DIR/index.html"
URL="file://$INDEX"

echo "Ready: $URL"

if command -v xdg-open >/dev/null 2>&1; then
  xdg-open "$URL" >/dev/null 2>&1 &
elif command -v open >/dev/null 2>&1; then
  open "$URL" >/dev/null 2>&1 &
else
  echo "Open the address above in a browser."
fi
