#!/bin/sh
#
# FreeBSD pkg pre-deinstall script for suricatavel-agent
#

PKG_PREFIX="${PKG_PREFIX:-/usr/local}"
INSTALL_DIR="${PKG_PREFIX}/suricatavel-agent"
SUPERVISOR_CONF="${PKG_PREFIX}/etc/supervisord.d/suricatavel-agent.conf"

if command -v supervisorctl >/dev/null 2>&1; then
    supervisorctl stop suricatavel-agent:* 2>/dev/null || true
    supervisorctl remove suricatavel-agent 2>/dev/null || true
    supervisorctl reread 2>/dev/null || true
    supervisorctl update 2>/dev/null || true
fi

if [ -f "${SUPERVISOR_CONF}" ]; then
    rm -f "${SUPERVISOR_CONF}"
fi

if service suricatavel_agent status >/dev/null 2>&1; then
    service suricatavel_agent stop
fi

CRON_CMD="cd ${INSTALL_DIR} && ${PKG_PREFIX}/bin/php artisan schedule:run >> /dev/null 2>&1"
if grep -Fq "${CRON_CMD}" /etc/crontab; then
    grep -Fv "${CRON_CMD}" /etc/crontab > /etc/crontab.tmp && mv /etc/crontab.tmp /etc/crontab
fi