#!/usr/bin/env bash
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x
source "$PLUGIN_CORE_AVAILABLE_PATH/common/functions"

trigger-apps-post-delete() {
  declare desc="apps post-delete plugin trigger"
  declare trigger="post-delete"
  declare APP="$1"
  local IMAGE_REPO=$(get_app_image_repo "$APP")

  if [[ -n "$APP" ]]; then
    # remove contents for apps that are symlinks to other folders
    rm -rf "${DOKKU_ROOT:?}/$APP/" >/dev/null
    # then remove the folder and/or the symlink
    rm -rf "${DOKKU_ROOT:?}/$APP" >/dev/null
  fi

  # shellcheck disable=SC2046
  "$DOCKER_BIN" image rm $("$DOCKER_BIN" image list --quiet "$IMAGE_REPO" | xargs) &>/dev/null || true
}

trigger-apps-post-delete "$@"
