#!/usr/bin/env bash
set -euo pipefail
[[ $(uname -s) == Linux && $(uname -m) == x86_64 ]] || { echo 'Linux x64 required.' >&2; exit 1; }
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)
root=$(dirname -- "$script_dir")
if (($#)); then
    [[ $# == 2 && $1 == --install-root && $2 == /* ]] || { echo 'Use --install-root /absolute/path.' >&2; exit 1; }
    root=$2
fi
root=$(realpath -m -- "$root")
[[ -d $root/bin && ! -L $root/bin && -f $root/bin/.ds1-receipt ]] || { echo 'Registered installation required.' >&2; exit 1; }
[[ $(cat "$root/bin/.ds1-receipt") == "$(printf 'ds1cli\n%s' "$root")" ]] || { echo 'Invalid receipt.' >&2; exit 1; }
mkdir -- "$root/.lifecycle-lock" 2>/dev/null || { echo 'Another lifecycle operation is active.' >&2; exit 1; }
trap 'rmdir -- "$root/.lifecycle-lock"' EXIT
if [[ -f $root/bin/.ds1-link ]]; then
    link=$(cat "$root/bin/.ds1-link")
    if [[ $link == /* && -L $link && $(readlink -- "$link") == "$root/bin/ds1cli" ]]; then rm -- "$link"; fi
fi
# The receipt names this dedicated root; data/keyrings/cache live outside bin.
rm -rf -- "$root/bin"
printf 'Uninstalled ds1cli; user data and configuration preserved.\n'
