#!/bin/sh
# prerm script for wazuh-manager

set -e
DIR="/var/ossec"

case "$1" in
    upgrade|deconfigure)

    ;;

    remove)
      # Stop the services before uninstalling the package
      # Check for systemd
      if command -v systemctl > /dev/null 2>&1 && systemctl > /dev/null 2>&1 && systemctl is-active --quiet wazuh-manager > /dev/null 2>&1; then
          systemctl stop wazuh-manager > /dev/null 2>&1
      # Check for SysV
      elif command -v service > /dev/null 2>&1 && service wazuh-manager status 2>/dev/null | grep "running" > /dev/null 2>&1; then
          service wazuh-manager stop > /dev/null 2>&1
      fi
      ${DIR}/bin/wazuh-control stop > /dev/null 2>&1

      # Purging files
      rm -rf ${DIR}/stats/*
      rm -rf ${DIR}/queue/*
      rm -rf ${DIR}/var/*
      rm -rf ${DIR}/framework/*

      # Save the configuration files in ${DIR}/tmp/conffiles
      mkdir -p ${DIR}/tmp/conffiles

      # Save the client.keys
      if [ -f ${DIR}/etc/client.keys ]; then
        cp -p ${DIR}/etc/client.keys ${DIR}/tmp/conffiles
      fi
      # Save the local_internal_options.conf
      if [ -f ${DIR}/etc/local_internal_options.conf ]; then
        cp -p ${DIR}/etc/local_internal_options.conf ${DIR}/tmp/conffiles
      fi
      # Save the ossec.conf
      if [ -f ${DIR}/etc/ossec.conf ]; then
        cp -p ${DIR}/etc/ossec.conf ${DIR}/tmp/conffiles
      fi
      # Save the lists
      if [ -d ${DIR}/etc/lists ]; then
        cp -pr ${DIR}/etc/lists ${DIR}/tmp/conffiles
      fi
      # Save the rootcheck files
      if [ -d ${DIR}/etc/rootcheck ]; then
        cp -pr ${DIR}/etc/rootcheck ${DIR}/tmp/conffiles
      fi
      # Save the agent.conf from the group default
      mkdir -p ${DIR}/tmp/conffiles/shared/default
      if [ -f ${DIR}/etc/shared/default/agent.conf ]; then
        cp -p ${DIR}/etc/shared/default/agent.conf ${DIR}/tmp/conffiles/shared/default
      fi
      # Save the api.yaml
      if [ -f ${DIR}/api/configuration/api.yaml ]; then
        cp -p ${DIR}/api/configuration/api.yaml ${DIR}/tmp/conffiles
        rm -rf ${DIR}/api/*
      fi
    ;;

    failed-upgrade)
      if [ -f ${DIR}/bin/wazuh-control ]; then
	       ${DIR}/bin/wazuh-control stop > /dev/null 2>&1
      fi
    ;;

    *)
        echo "prerm called with unknown argument \`$1'" >&2
        exit 0
    ;;

esac

exit 0
