#!/bin/bash
# Atomicorp, Inc
# Copyrigth 2024
# Summary: freshclam wrapper


# Globals
SIG_DIR="/var/lib/clamav/"
DEBUG=0
LOG_FILE="/var/ossec/logs/atomicorp-api.log"
TEMP_DIR="/tmp/clamav_downloads"
MODULE_NAME="atomicorp-api-module-freshclam"

#####################################
# Functions
#####################################
source /var/ossec/lib/atomicorp-functions.sh

function update_from_hub() {

    get_hub_ip
    SERVER="https://${HUB_IP}/channels/rules/anti-malware/"

    if [[ ${TEMP_DIR} == "/" ]]; then
        echo "TEMP_DIR is set to /, aborting"
        exit 1
    fi

    if [ -d $TEMP_DIR ]; then
        rm -rf ${TEMP_DIR}
    fi
    mkdir -p ${TEMP_DIR}

    if [[ ${FRESHCLAM_LINUX_SIGS} == "yes" ]]; then

        EXTENSIONS="fp hdb hdu hsb hsu idb ign2 ldb ldu ndb ndu sfp"
        for ext in $EXTENSIONS; do
            download -k ${SERVER}/Atomicorp-Linux.${ext}  $TEMP_DIR/Atomicorp-Linux.${ext}
            if [ $? -ne 0 ]; then
                exit 1
            fi
        done

        if [[ ${SIG_DIR} == "/" ]]; then
            echo "SIG_DIR is set to /, aborting"
            exit 1
        fi
        rm -rf ${SIG_DIR}/*
        cp ${TEMP_DIR}/* ${SIG_DIR}/
        rm -rf ${TEMP_DIR}
        if [[ $DEBUG -ge 1 ]]; then
	        log_event "DEBUG1: update_from_hub: Clamav_owner is ${CLAMAV_OWNER} and Clamav_group is ${CLAMAV_GROUP}"
        fi
        /usr/bin/chown -R ${CLAMAV_OWNER}:${CLAMAV_GROUP} ${SIG_DIR}/*
    fi

}

#####################################
# Main
#####################################
dist_detection

if [ -d /var/ossec/queue/sockets/ ]; then
        AGENT_INFO_PATH=/var/ossec/queue/sockets/
elif [ -d /var/ossec/queue/ossec/ ]; then
        AGENT_INFO_PATH=/var/ossec/queue/ossec/
fi

ID=$(sed '3q;d' ${AGENT_INFO_PATH}/.agent_info)

if [ -f /var/ossec/etc/shared/${ID}.malware-detection ]; then
    CONFIG_FILE="/var/ossec/etc/shared/${ID}.malware-detection"
elif [ -f /var/ossec/etc/shared/malware-detection ]; then
    CONFIG_FILE="/var/ossec/etc/shared/malware-detection"
else
    if [[ $DEBUG -ge 1 ]]; then
        log_event "Neither ${ID}.malware-detection nor malware-detection found."
    fi
    exit 
fi


get_freshclam_conf
if [ ! -d ${SIG_DIR} ]; then
    mkdir -p ${SIG_DIR}
    if [ $DEBUG -ge 1 ]; then
        log_event "DEBUG1: freshclam: clamav_owner and clamav_group are ${CLAMAV_OWNER}:${CLAMAV_GROUP}"
    fi
    chown ${CLAMAV_OWNER}:${CLAMAV_GROUP} ${SIG_DIR}
fi

# Pull from the hub server
if [[ $FRESHCLAM_FEED_TYPE == "hub" ]]; then
    update_from_hub
else
    if [ $PKG == "pkg" ]; then
        update_from_hub
        svcadm restart svc:/network/cswclamd:default
    elif [ $PKG == "aix" ]; then
        if [ -x /opt/atomicorp/bin/freshclam ]; then
            /opt/atomicorp/bin/freshclam
        else
            /opt/freeware/bin/freshclam
        fi
    else
    	/usr/bin/freshclam 
    fi
fi


