#!/bin/sh
set -eu

target_volume="${3:-/}"
if [ -z "$target_volume" ]; then
  target_volume="/"
fi

link_path="$target_volume/usr/local/bin/welles"
expected="/Applications/Welles.app/Contents/Resources/welles"

if [ ! -e "$link_path" ] && [ ! -L "$link_path" ]; then
  exit 0
fi

if [ ! -L "$link_path" ]; then
  echo "$link_path already exists and is not a symlink. Move it before installing the bundled welles CLI." >&2
  exit 1
fi

target="$(/usr/bin/readlink "$link_path")"
case "$target" in
  "$expected"|*"/Welles.app/Contents/Resources/welles")
    exit 0
    ;;
  *)
    echo "$link_path points at a different tool. Move it before installing the bundled welles CLI." >&2
    exit 1
    ;;
esac
