#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib/texise-deploy.sh
source "${SCRIPT_DIR}/lib/texise-deploy.sh"

texise_require_root

purge=false
if [[ "${1:-}" == '--purge' ]]; then
  purge=true
elif [[ $# -gt 0 ]]; then
  texise_die 'Usage: scripts/uninstall.sh [--purge]'
fi

systemctl disable --now texise.service >/dev/null 2>&1 || true
rm -f "${TEXISE_SYSTEMD_UNIT}" /usr/local/bin/texise-license /usr/local/bin/texise-saas
systemctl daemon-reload

if command -v a2dissite >/dev/null 2>&1; then
  a2dissite app.texise.com.conf >/dev/null 2>&1 || true
fi
rm -f "${TEXISE_APACHE_SITE}"
if command -v apache2ctl >/dev/null 2>&1 && apache2ctl configtest >/dev/null 2>&1; then
  systemctl reload apache2 >/dev/null 2>&1 || true
fi

rm -rf "${TEXISE_DIST_DIR}" "${TEXISE_INSTALL_ROOT}/dist.next" "${TEXISE_PREVIOUS_DIST_DIR}" "${TEXISE_RUNTIME_DIR}"

if [[ "${purge}" == true ]]; then
  rm -rf "${TEXISE_CONFIG_DIR}" "${TEXISE_DATA_DIR}" "${TEXISE_BLOG_MEDIA_ROOT}"
  texise_log 'Removed TeXise runtime, generated browser builds, public_html server data/media, configuration, and signing material.'
else
  texise_log "Removed TeXise runtime and generated browser builds. Preserved ${TEXISE_CONFIG_DIR}."
  texise_log 'Use scripts/uninstall.sh --purge to remove configuration, persistent public_html server data/media, and signing material.'
fi

texise_log "Source code was preserved at ${TEXISE_INSTALL_ROOT}. Remove it manually only when you intend to delete the source tree."
