#!/usr/bin/env bash
#
# show - show given file(s) in finder.app (default: current directory)

# shellcheck shell=bash

[ "$#" -eq 0 ] && set -- .

# build array of paths for applescript
paths=()
for path; do
  # make sure each path exists
  if ! [ -e "${path}" ]; then
    echo "show: ${path}: No such file or directory"
    continue
  fi
  # re-implement "readlink -f" ("realpath") for darwin
  # ("cd .. >/dev/null" hides CDPATH noise)
  [ -d "${path}" ] \
    && path="$(cd -- "${path}" >/dev/null && pwd)" \
    || path="$(cd -- "$(dirname -- "${path}")" >/dev/null \
      && echo "${PWD}/$(basename -- "${path}")")"

  paths+=("${path}")
done
[ "${#paths[@]}" -eq 0 ] && exit

paths_for_osascript=''
# group all output to pipe through osacript
{
  echo 'tell application "Finder"'
  # "reveal" would select only last file
  printf '%s' 'select {'

  # use `POSIX file "/path/to/file.ext"` applescript syntax
  printf -v paths_for_osascript $'POSIX file "%s", ' "${paths[@]//\"/\\\"}"
  paths_for_osascript="${paths_for_osascript%$', '}"
  printf '%s' "${paths_for_osascript}"

  echo '}'
  echo 'activate'
  echo 'end tell'
} | osascript
