#!/usr/bin/env bash

set -euo pipefail

force=false
case "${1:-}" in
  "") ;;
  --force) force=true ;;
  *)
    echo "Usage: $0 [--force]" >&2
    exit 2
    ;;
esac

if [[ "$(uname -s)" != "Darwin" ]]; then
  echo "Error: this script only supports macOS." >&2
  exit 1
fi
command -v pgrep >/dev/null 2>&1 || {
  echo "Error: pgrep is not installed." >&2
  exit 1
}

if pgrep -xq Safari 2>/dev/null; then
  if [[ "$force" != true ]]; then
    echo "Error: Safari is running. Quit it and run this script again." >&2
    echo "Use --force only if you understand the risk of deleting an open database." >&2
    exit 1
  fi
  echo "Warning: Safari is running; continuing because --force was supplied." >&2
else
  pgrep_status=$?
  if ((pgrep_status != 1)); then
    echo "Error: unable to determine whether Safari is running." >&2
    exit 1
  fi
fi

safari_library_path="$HOME/Library/Safari"
history_files=(
  "$safari_library_path/History.db"
  "$safari_library_path/History.db-shm"
  "$safari_library_path/History.db-wal"
)
files_to_remove=()

for file in "${history_files[@]}"; do
  if [[ -e "$file" ]]; then
    files_to_remove+=("$file")
  fi
done

if ((${#files_to_remove[@]} == 0)); then
  echo "No Safari History.db files were found in $safari_library_path."
  exit 0
fi

echo "Removing the following local Safari history database files:"
printf '  %s\n' "${files_to_remove[@]}"
rm -f -- "${files_to_remove[@]}"

for file in "${files_to_remove[@]}"; do
  if [[ -e "$file" ]]; then
    echo "Error: failed to remove $file." >&2
    exit 1
  fi
done

echo "Safari's local history database files were removed."
echo "Safari will recreate them the next time it starts."
