#!/bin/zsh
#
# md2pdf-install-quickaction — install (or refresh) the "Convert to PDF"
# Finder Quick Action.
#
# Symlinks the version-controlled workflow bundle from the dotfiles repo into
# ~/Library/Services so edits in the repo take effect without reinstalling,
# then flushes the Services cache so the menu item appears immediately.
#
# Usage: md2pdf-install-quickaction [--copy]
#   --copy   Install a copy instead of a symlink (use if you prefer the
#            installed action to be independent of the repo).

emulate -L zsh
set -o pipefail

prog=${0:t}
die() { print -u2 "$prog: $*"; exit 1; }

local mode=symlink
[[ $1 == --copy ]] && mode=copy
[[ -n $1 && $1 != --copy ]] && die "unknown argument: $1 (only --copy is supported)"

# Source bundle lives next to this script: ../macos/md2pdf.workflow
local src="${0:A:h:h}/macos/md2pdf.workflow"
[[ -d $src ]] || die "workflow bundle not found at $src"

local services="$HOME/Library/Services"
local dest="$services/md2pdf.workflow"

mkdir -p "$services" || die "could not create $services"

# Remove any prior install (symlink or directory) so we start clean.
if [[ -L $dest || -e $dest ]]; then
  rm -rf -- "$dest" || die "could not remove existing $dest"
fi

if [[ $mode == symlink ]]; then
  ln -s "$src" "$dest" || die "could not symlink workflow into $services"
  print -- "✓ linked $dest -> $src"
else
  cp -R "$src" "$dest" || die "could not copy workflow into $services"
  print -- "✓ copied workflow to $dest"
fi

# Refresh the Services/Quick Actions registry so the item shows up now.
local pbs="/System/Library/CoreServices/pbs"
if [[ -x $pbs ]]; then
  "$pbs" -flush 2>/dev/null
  print -- "✓ flushed Services cache"
fi
# Nudge the Extensions/Quick Actions registration too (harmless if absent).
/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister \
  -f "$dest" 2>/dev/null

cat <<EOF

Installed. To use it:
  • In Finder, right-click one or more .md files
  • Choose  Quick Actions ▸ Convert to PDF (md2pdf)   (may be under a "..." submenu)

If it doesn't appear immediately, toggle it on in:
  System Settings ▸ Keyboard ▸ Keyboard Shortcuts… ▸ Services ▸ Files and Folders
(or log out and back in to fully refresh the Services menu).
EOF
