#!/bin/sh

confdir="$XDG_CONFIG_HOME"
if [ -z "$confdir" ]; then
  confdir=~/.config/
fi
agtdata="${confdir}picus_agent/"

if [ -e $agtdata ]; then
  # If root, try to remove the updater service
  if [ "$(id -u)" = "0" ]; then
    # First, check if systemctl exists at all
    if ! command -v systemctl >/dev/null 2>&1; then
      echo "# systemctl does not exist, skipping updater service removal"
    else
      echo "# Removing the updater service"
      ctlog=$(systemctl stop com.picussecurity.updater.service 2>&1 &&
        systemctl disable com.picussecurity.updater.service 2>&1) ||
        (
          echo "# Cannot remove updater service, might already be removed. Output:"
          echo "  $ctlog"
        )
      echo "# Removing updater files"
      rm -rf /etc/systemd/system/com.picussecurity.updater.service
      rm -rf /usr/local/bin/picus_updater
      echo "# Updater deleted."
    fi
  fi

  # Kill agent process if pidfile exists
  pidfile="${agtdata}agent.pid"
  if [ -e agent.pid ]; then
    agtpid="$(cat agent.pid)" &&
      echo "# Killing agent process with PID $agtpid" &&
      kill "$agtpid"
  else
    echo "# Missing pidfile at $pidfile, agent process might be dead"
  fi
  # Now remove all agent data
  echo "# Removing agent data from path $agtdata"
  rm -rf "$agtdata"
  echo "# Agent data deleted."
else
  echo "# Agent data directory does not exist at $agtdata, cannot run uninstall"
fi
