#!/usr/bin/env zsh
set -euo pipefail

execute=false
if [[ ${1:-} == '--execute' ]]; then
  execute=true
  shift
fi

if [[ $# -gt 0 ]]; then
  print -u2 'Usage: rename-iso.zsh [--execute]'
  exit 2
fi

# Requires Obsidian app running and CLI enabled.
# Adjust OBSIDIAN_CLI to the command you actually use (e.g. `obsidian`).
: ${OBSIDIAN_CLI:=obsidian}

files=(ISO27001-2023-NL-*.md(N))
if (( ${#files} == 0 )); then
  print 'No matching files found.'
  exit 0
fi

for src in "$files[@]"; do
  base=${src:t}
  if [[ $base =~ '^ISO27001-2023-NL-([0-9]+\.?[0-9]*)\.md$' ]]; then
	version=${match[1]}
	target="c-${version}.md"
	if [[ $src == $target ]]; then
	  print "SKIP  $src"
	  continue
	fi
	print "SRC   $src"
	print "DEST  $target"
	if $execute; then
	  "$OBSIDIAN_CLI" rename file="$src" name="$target"
	fi
  else
	print -u2 "WARN  skipped (pattern mismatch): $src"
  fi
done
