#!/bin/sh
#
# open-pdf-to-page - open pdf at a given page number
#
# note: requires that your terminal application has accessibility permissions
#
# ---
# source: https://github.com/jeremyf/dotzshrc/blob/main/bin/open-pdf-to-page

file="$1"

if [ -z "$1" ]; then
  echo "You'll need to provide a path"
  exit 1
fi

if [ -z "$2" ]; then
  page=0
else
  page="$2"
fi

# applescript
osascript <<EOF

set pageNumber to $page
set fileName to "$file"

set posixFile to POSIX file fileName
tell application "Finder" to open posixFile

delay 0.1
tell application "System Events"
  tell application "Preview"
    # x, y, width, height
    set bounds of front window to {0, 0, 800, 900}
  end tell

  if (pageNumber = 0) then

  else
  keystroke "g" using {option down, command down}
  keystroke pageNumber
  delay 0.1

  # Return
  key code 36
end if
end tell

EOF
