#!/bin/bash -e
SOURCE="${BASH_SOURCE[0]}"
# Get the actual physical location of the zshot binary
while [ -L "$SOURCE" ]; do
  DIR="$(cd -P "$(dirname "$SOURCE")" && pwd)"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
done
SCRIPT_DIR="$(cd -P "$(dirname "$SOURCE")" && pwd)"
if [[ "$(uname)" == "Darwin" ]]; then
  ZSHOT_DIRECTORY="${ZSHOT_DIRECTORY:-""}"
  if [ ! -d "${ZSHOT_DIRECTORY}" ]; then
    ZSHOT_DIRECTORY="${SCRIPT_DIR}"
  fi
  if [ -z "${ZSHOT_DIRECTORY}" ];  then
    ZSHOT_DIRECTORY="${SCRIPT_DIR}"
  fi
  ZSHOT_APP_PATH="${ZSHOT_DIRECTORY}/zshot_app.app/Contents/MacOS/zshot_app"
  if [ ! -f "${ZSHOT_APP_PATH}" ]; then
    echo "Could not locate zshot app ($ZSHOT_APP_PATH) in ${ZSHOT_DIRECTORY}"
    exit 1
  fi
  exec "${ZSHOT_APP_PATH}" "${@}"
else
  # Resolution order: explicit env override, the tarball payload next to this
  # script, the system install, then the script's own directory.
  if [ -z "${ZSHOT_DIRECTORY:-}" ]; then
    for candidate in "${SCRIPT_DIR}/lib/zshot" "/usr/lib/zshot"; do
      if [ -f "${candidate}/zshot" ]; then
        ZSHOT_DIRECTORY="${candidate}"
        break
      fi
    done
  fi
  if [ ! -d "${ZSHOT_DIRECTORY:-}" ]; then
    ZSHOT_DIRECTORY="${SCRIPT_DIR}"
  fi
  if [ ! -f "${ZSHOT_DIRECTORY}/zshot" ]; then
    echo "Could not locate zshot binary in ${ZSHOT_DIRECTORY}"
    exit 1
  fi
  exec "${ZSHOT_DIRECTORY}/zshot" "${@}"
fi
