#!/bin/bash

# This script will automatically update the rules on a snort device
# without human intervention. update log will be placed at
# /opt/snort/update.log for review

# "current" is where we will store snort rules backups at
# "new" is where the new downloads will take place.

LOGFILE="/opt/snort/update.log"

mkdir -p /opt/snort/gsi-scripts/current
mkdir -p /opt/snort/gsi-scripts/new

echo "#####Snort auto-update running on `date`#####" >> $LOGFILE

wget https://phonehome.gsihosting.com/downloads/snort/rules.tar.gz -O /opt/snort/gsi-scripts/new/rules.tar.gz --no-check-certificate &> /dev/null

if [ $? = 1 ]; then
        echo "`date` - download failed" >> $LOGFILE
		exit
else
        echo "`date` - download ok" >> $LOGFILE
fi

cd /opt/snort/gsi-scripts/new/ ; tar -zxvf rules.tar.gz &> /dev/null

if [ $? = 2 ]; then
        echo "`date` - extraction failed" >> $LOGFILE
		exit
else
        echo "`date` - extraction ok" >> $LOGFILE
fi

zip -r /opt/snort/gsi-scripts/current/snort`date +%N`.zip /opt/snort/rules/

if [ $? != 0 ]; then
        echo "`date` - current snort backup failed" >> $LOGFILE
		exit
else
        echo "`date` - current snort backup ok" >> $LOGFILE
fi

################# Stop snort
/etc/init.d/snort >> $LOGFILE

cp -f /opt/snort/gsi-scripts/new/rules/* /opt/snort/rules/ >> $LOGFILE

if [ $? != 0 ]; then
        echo "`date` - new rule file copy failed. please perform manual rollback." >> $LOGFILE
		exit
else
        echo "`date` - new rule file copy ok" >> $LOGFILE
fi

######################################### rebuild rule files
bash /opt/snort/gsi-scripts/buildrules.sh >> $LOGFILE


################# Starts snort
/etc/init.d/snort >> $LOGFILE

####################################### Final cleanup
rm -rf /opt/snort/gsi-scripts/new/*
