#!/bin/sh
# After uninstalling. The data stays in its shared folder unless the uninstall wizard was told to delete it; the saved
# settings go always. An upgrade runs this script of the old version too (SYNOPKG_PKG_STATUS=UPGRADE), and keeps
# everything.
# shellcheck disable=SC2154 # wizard_* come from WIZARD_UIFILES/uninstall_uifile
. "$(dirname "$0")/common"

[ "${SYNOPKG_PKG_STATUS:-}" = UNINSTALL ] || exit 0
settings=$(find_settings) || exit 0

# Only an uninstall of a KumoYami that ran: DSM also runs this script when it rolls back a failed installation, and
# then wizard_delete_data came as true (0.1.5-0002 on a DS920+) although nobody saw the uninstall wizard
ran="$(dirname "$settings")/$RAN_NAME"
if [ "${wizard_delete_data:-false}" = true ] && [ -f "$ran" ]; then
  share=$(setting "$settings" DATA_SHARE)
  sub=$(setting "$settings" DATA_SUBFOLDER)
  base=""
  if [ -n "$share" ] && valid_share "$share"; then
    base=$(share_path "$share")
  fi
  dir="$base${sub:+/$sub}"
  # Only a folder that holds KumoYami's data (kv.json), and never the shared folder itself (only root can delete it)
  if [ -n "$base" ] && [ -f "$dir/kv.json" ]; then
    if [ -n "$sub" ]; then
      rm -rf "$dir"
    else
      find "$dir" -mindepth 1 -maxdepth 1 ! -name '#recycle' ! -name '@eaDir' -exec rm -rf {} +
    fi
    say "Datos de KumoYami borrados de $dir. La carpeta compartida $share sigue en DSM: bórrala en Panel de control → Carpeta compartida si ya no la quieres." \
      "KumoYami's data deleted from $dir. The shared folder $share is still in DSM: delete it in Control Panel → Shared Folder if you no longer want it."
  else
    say "No se ha borrado nada: no se encontraron datos de KumoYami en la carpeta compartida $share." \
      "Nothing was deleted: no KumoYami data was found in the shared folder $share."
  fi
fi
rm -f "$settings" "$ran"
exit 0
