#!/bin/sh
set -eu

usage() {
  cat <<'EOF'
Install movcli into a user-writable global bin directory.

Usage:
  install-movcli [options]

Options:
  --bin-dir <dir>   Install wrapper into this directory. Defaults to ~/.local/bin.
  --name <name>     Installed command name. Defaults to movcli.
  --force           Replace an existing command at the target path.
  -h, --help        Show this help.

Examples:
  ./bin/install-movcli
  ./bin/install-movcli --bin-dir /usr/local/bin --force
EOF
}

fail() {
  printf 'install-movcli: %s\n' "$1" >&2
  exit 1
}

BIN_DIR="${MOVSCRIPT_CLI_INSTALL_BIN_DIR:-${HOME:-}/.local/bin}"
COMMAND_NAME="movcli"
FORCE=0

while [ "$#" -gt 0 ]; do
  case "$1" in
    --bin-dir)
      [ "$#" -ge 2 ] || fail "--bin-dir requires a value"
      BIN_DIR="$2"
      shift 2
      ;;
    --name)
      [ "$#" -ge 2 ] || fail "--name requires a value"
      COMMAND_NAME="$2"
      shift 2
      ;;
    --force)
      FORCE=1
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      fail "unknown option: $1"
      ;;
  esac
done

[ -n "$BIN_DIR" ] || fail "could not resolve install bin directory; pass --bin-dir <dir>"

SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
SOURCE="$SCRIPT_DIR/movcli"
TARGET_DIR=$(mkdir -p "$BIN_DIR" && cd "$BIN_DIR" && pwd)
TARGET="$TARGET_DIR/$COMMAND_NAME"

[ -x "$SOURCE" ] || fail "movcli executable not found: $SOURCE"

case "$COMMAND_NAME" in
  ''|*/*)
    fail "--name must be a command name, not a path"
    ;;
esac

if [ -e "$TARGET" ] || [ -L "$TARGET" ]; then
  if [ "$FORCE" -ne 1 ]; then
    fail "$TARGET already exists; pass --force to replace it"
  fi
  rm -f "$TARGET"
fi

cat > "$TARGET" <<EOF
#!/bin/sh
exec "$SOURCE" "\$@"
EOF
chmod 755 "$TARGET"

printf 'Installed %s -> %s\n' "$COMMAND_NAME" "$SOURCE"

case ":${PATH:-}:" in
  *":$TARGET_DIR:"*) ;;
  *)
    printf '\n%s is not currently on PATH.\n' "$TARGET_DIR"
    printf 'Add this to your shell profile, then restart the terminal:\n'
    printf '  export PATH="%s:$PATH"\n' "$TARGET_DIR"
    ;;
esac

printf '\nVerify with:\n'
printf '  %s --help\n' "$COMMAND_NAME"
