#!/bin/bash
# Copyright Security Onion Solutions LLC and/or licensed to Security Onion Solutions LLC under one
# or more contributor license agreements. Licensed under the Elastic License 2.0 as shown at 
# https://securityonion.net/license; you may not use this file except in compliance with the
# Elastic License 2.0.

NOROOT=1
. /usr/sbin/so-common

echo "Starting to check for yara rule updates at $(date)..."

newcounter=0
excludedcounter=0
excluded_rules=({{ EXCLUDEDRULES | join(' ') }})

# Pull down the SO Rules
SORULEDIR=/nsm/rules/yara
OUTPUTDIR=/opt/so/saltstack/local/salt/strelka/rules

mkdir -p $OUTPUTDIR
# remove all rules prior to copy so we can clear out old rules
rm -f $OUTPUTDIR/*

for i in $(find $SORULEDIR -name "*.yar" -o -name "*.yara"); do
  rule_name=$(echo $i | awk -F '/' '{print $NF}')
  if [[ ! "${excluded_rules[*]}" =~ ${rule_name} ]]; then
    echo "Adding rule: $rule_name..."
    cp $i $OUTPUTDIR/$rule_name
    ((newcounter++))
  else
    echo "Excluding rule: $rule_name..."
    ((excludedcounter++))
  fi
done

if [ "$newcounter" -gt 0 ] || [ "$excludedcounter" -gt 0 ];then
  echo "$newcounter rules added."
  echo "$excludedcounter rule(s) excluded."
fi

echo "Finished rule updates at $(date)..."
