#!/usr/bin/env bash
set -euo pipefail
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)
root=${DS1_INSTALL_ROOT:-$(dirname -- "$script_dir")}
plan=0 no_path=0
while (($#)); do
 case "$1" in --install-root) root=$2; shift 2;; --plan) plan=1; shift;; --no-path) no_path=1; shift;; *) echo 'Use --install-root PATH [--plan] [--no-path].' >&2; exit 2;; esac
done
root=$(realpath -m -- "$root")
link=''
if [[ -f $root/.ds1-link ]]; then link=$(cat "$root/.ds1-link");
elif [[ -f $root/bin/.ds1-link ]]; then link=$(cat "$root/bin/.ds1-link"); fi
args=(package uninstall --target "$root")
((plan == 0)) || args+=(--plan)
"$root/bin/ds1cli" "${args[@]}"
((plan == 0)) || exit 0
if [[ $no_path == 0 && -n $link && $link == /* && -L $link && $(readlink -- "$link") == "$root/bin/ds1cli" ]]; then
 printf 'Remove only the managed command link? [s/N] '
 read -r answer </dev/tty
 case "$answer" in s|sim|y|yes) rm -- "$link"; rm -f -- "$root/.ds1-link";; esac
fi
