#!/usr/bin/env bash
set -euo pipefail
if command -v sudo >/dev/null 2>&1; then
  SUDO="sudo"
else
  SUDO=""
fi
echo "[uninstall] Stopping and disabling service..."
${SUDO} systemctl stop osm 2>/dev/null || true
${SUDO} systemctl disable osm 2>/dev/null || true
echo "[uninstall] Removing systemd unit..."
${SUDO} rm -f /etc/systemd/system/osm.service
${SUDO} systemctl daemon-reload || true
APP_DIR=/opt/osm
if [ -d "$APP_DIR" ]; then
  echo "[uninstall] Removing agent directory: $APP_DIR"
  ${SUDO} rm -rf "$APP_DIR"
fi
echo "[uninstall] Removing CLI wrapper..."
${SUDO} rm -f /usr/local/bin/osm /usr/local/bin/sma
echo "[uninstall] Removing Exim ACL include files..."
${SUDO} rm -f /etc/exim.acl_check_recipient.pre.osm.conf /etc/exim.acl_script.pre.osm.conf
echo "[uninstall] Cleaning include references from Exim base include files..."
BASE_RECIP=/etc/exim.acl_check_recipient.pre.conf
BASE_SCRIPT=/etc/exim.acl_script.pre.conf
if [ -f "$BASE_RECIP" ]; then
  ${SUDO} sed -i '\|/etc/exim.acl_check_recipient.pre.osm.conf|d' "$BASE_RECIP" || true
fi
if [ -f "$BASE_SCRIPT" ]; then
  ${SUDO} sed -i '\|/etc/exim.acl_script.pre.osm.conf|d' "$BASE_SCRIPT" || true
fi
echo "[uninstall] Backing up and removing OSM virtual control lists..."
TS=$(date +%Y%m%d%H%M%S)
for f in /etc/virtual/osm_hold /etc/virtual/osm_disable; do
  if [ -f "$f" ]; then
    ${SUDO} cp -f "$f" "${f}.bak-${TS}" || true
    ${SUDO} rm -f "$f"
  fi
done
echo "[uninstall] Reloading Exim..."
${SUDO} systemctl reload exim 2>/dev/null || ${SUDO} systemctl reload exim4 2>/dev/null || true
echo "[uninstall] Done. Backups (if any) are in /etc/virtual/*.bak-${TS}"