#!/bin/bash
#
# This script exit codes
# 0 means OK
# 1 some error or csf is not installed
#

function is_csf_installed {
  if which csf >/dev/null 2>&1; then
    echo "csf is installed"
    return 0
  else
    echo "csf is not installed"
    return 1
  fi
}

function enable_csf {
  systemctl start csf
  systemctl start lfd
  csf --enable # add csf to autostart
}

function disable_csf {
  systemctl stop csf
  systemctl stop lfd
  csf --disable # remove csf from autostart
}

function add_bins_to_pignore {
    BINS_TO_IGNORE="exe:/opt/alt/python35/bin/python3.5 \
                    exe:/var/ossec/bin/ossec-monitord \
                    exe:/var/ossec/bin/ossec-analysisd"
    ignore_file=/etc/csf/csf.pignore
    should_restart=false

    for exe in $BINS_TO_IGNORE; do
        if ! grep -q $exe $ignore_file ; then
            echo $exe >> $ignore_file
            should_restart=true
        fi
    done

    if $should_restart; then
        echo 'Restarting CSF to apply pignore changes'
        csf --restartall > /dev/null
    fi
}

function coop_install {
  add_bins_to_pignore
  # todo: get from config!
  local out=`csf --add 148.251.130.176 'imunify360 server' 2>&1`
  local rc=$?
  test $rc = 0 && return 0
 (echo "$out" | grep "is in already") && return 0
  return $rc
}

if [ "$1" = "" ] ; then
    echo "Usage: $0 enable/disable/status/coop_install"
    exit 1
fi
if [ "$1" = "status" ] ; then
    is_csf_installed
    exit $?
fi
if [ "$1" = "enable" ]
then
    is_csf_installed >/dev/null || exit 1
    enable_csf
    exit $?
fi
if [ "$1" = "disable" ]
then
    is_csf_installed >/dev/null || exit 1
    disable_csf
    exit $?
fi
if [ "$1" = "coop_install" ]
then
    is_csf_installed >/dev/null || exit 1
    coop_install
    exit $?
fi
