#!/usr/bin/env bash
set -eu

# adapted from https://github.com/johannes-wolf/cetz/blob/35c0868378cea5ad323cc0d9c2f76de8ed9ba5bd/scripts/package
# licensed under Apache License 2.0

. "$(dirname "${BASH_SOURCE[0]}")/setup"

if (( $# < 1 )) || [[ "${1:-}" == "help" ]]; then
  echo "uninstall TARGET"
  echo ""
  echo "Removes the package installed into a directory named '<name>/<version>'"
  echo "at TARGET. If TARGET is set to @local or @preview, the local Typst package"
  echo "directory will be used so that the package gets installed for local use."
  echo "The name and version are read from 'typst.toml' in the project root."
  echo ""
  echo "Local package prefix: $DATA_DIR/typst/package/local"
  echo "Local preview package prefix: $DATA_DIR/typst/package/preview"
  exit 1
fi

TARGET="$(resolve-target "${1:?Missing target path, @local or @preview}")"
echo "Install dir: $TARGET"

TARGET="${TARGET:?}/${PKG_PREFIX:?}/${VERSION:?}"
echo "Package to uninstall: $TARGET"
if [[ ! -e "${TARGET:?}" ]]; then
  echo "Package was not found."
elif rm -r "${TARGET:?}" 2>/dev/null; then
  echo "Successfully removed."
else
  echo "Removal failed."
fi
