#!/bin/bash
# Optional, separately distributed launcher for the App Store app.
set -euo pipefail
PATH=/usr/bin:/bin:/usr/sbin:/sbin

readonly APP_PATH=/Applications/PrismCompare.app
readonly APP_ID=jp.co.extrainnovation.PrismCompare
readonly VERSION=1.0.0

usage() {
  printf '%s\n' \
    'Usage: ksdiff [--] [LEFT RIGHT]' \
    '       ksdiff --check | --help | --version' \
    'Opens the App Store version of Prism Compare through macOS.' \
    'No merge, wait, label, snapshot or remote-upload protocol.'
}

check_only=false
case "${1-}" in
  --help|-h)
    [[ "$#" == 1 ]] || { usage >&2; exit 2; }
    usage
    exit 0
    ;;
  --version)
    [[ "$#" == 1 ]] || { usage >&2; exit 2; }
    printf 'Prism Compare CLI %s\n' "$VERSION"
    exit 0
    ;;
  --check)
    [[ "$#" == 1 ]] || { usage >&2; exit 2; }
    check_only=true
    shift
    ;;
  --) shift ;;
  -*) usage >&2; exit 2 ;;
esac

if [[ "$#" != 0 && "$#" != 2 ]]; then
  usage >&2
  exit 2
fi

if [[ ! -x "$APP_PATH/Contents/MacOS/PrismCompare" ]]; then
  printf 'Install Prism Compare from the App Store in %s first.\n' "$APP_PATH" >&2
  exit 1
fi
bundle_id=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$APP_PATH/Contents/Info.plist")
if [[ "$bundle_id" != "$APP_ID" ]]; then
  printf 'Unexpected application identifier at %s.\n' "$APP_PATH" >&2
  exit 1
fi
requirement='=identifier "jp.co.extrainnovation.PrismCompare" and anchor apple generic and (certificate leaf[field.1.2.840.113635.100.6.1.9] exists or certificate leaf[subject.OU] = "94UZ76XWYL")'
if ! /usr/bin/codesign --verify --strict -R "$requirement" "$APP_PATH"; then
  printf 'The Prism Compare application signature could not be verified.\n' >&2
  exit 1
fi

if $check_only; then
  printf 'Verified App Store application: %s\n' "$APP_PATH"
  exit 0
fi
for input in "$@"; do
  if [[ ! -e "$input" ]]; then
    printf 'Comparison input not found: %s\n' "$input" >&2
    exit 1
  fi
done
exec /usr/bin/open -a "$APP_PATH" -- "$@"
