#!/bin/bash

function usage () {
    echo "$0: [--warning] [--clean] [--silent]"
    echo "--warning - gives warning about this script and aborts"
    echo "--clean - clean twpol.txt instead of update it"
    echo "--silent - turn off messages, only errors are shown"
}

WARNING=No
CLEAN=No
UPDATE=Yes
SILENT=No

while [ $# -gt 0 ] ; do
    case $1 in
	--warning)
	    WARNING=Yes
	    shift
	    ;;
	--clean)
	    CLEAN=Yes
	    UPDATE=No
	    shift
	    ;;
	--silent)
	    SILENT=Yes
	    shift
	    ;;
	*)
	    usage
	    exit 1
    esac
done

if [ ${SILENT} = "No" ] ; then
    echo "To avoid possible undetected breakins pay attention to the"
    echo "following" 
    echo 
    echo "Before running this script confirm tripwire is updated and"
    echo "don't exist changes on the system files."

    if [ ${WARNING} = "Yes" ] ; then
	exit 0
    fi

    echo "Press enter to continue"
    read
fi

PACKNAME=tp-conf-srv
LIBDIR=/etc/${PACKNAME}
FILE=/etc/tripwire/twpol.txt

LINES=`wc -l < $FILE`
#echo $LINES

HEADERFILE=`/bin/tempfile`
MIDDLEFILE=`/bin/tempfile`
TAILFILE=`/bin/tempfile`

HEADERSEP="#### BEGIN Automatically Generated by ${PACKNAME} ####################"
TAILSEP="#### END Automatically Generated by ${PACKNAME} ######################"

if grep -q "$HEADERSEP" $FILE && grep -q "$TAILSEP" $FILE ; then

    grep -B${LINES} "$HEADERSEP" $FILE > $HEADERFILE
    grep -A${LINES} "$TAILSEP" $FILE > $TAILFILE

    if [ ${UPDATE} = "Yes" ] ; then
	shopt -s nullglob
	for file in /proc/[a-Z]* ; do
	    printf "$file\t-> \$(Device) ;\n" >> $MIDDLEFILE
	done
	cat $HEADERFILE $MIDDLEFILE $TAILFILE > $FILE
    fi
    if [ ${CLEAN} = "Yes" ] ; then
	cat $HEADERFILE $TAILFILE > $FILE
    fi
    if [ ${SILENT} = "No" ] ; then
	echo "If is the first time tripwire is run then initialize it using:"
	echo "dpkg-reconfigure tripwire ; tripwire -m i"
	echo "or"
	echo "twadmin -m F -S /etc/tripwire/site.key /etc/tripwire/twcfg.txt ; twadmin -m P -S /etc/tripwire/site.key /etc/tripwire/twpol.txt ; tripwire -m i "
	echo 
	echo "If the database alread exist then you need to update policy." 
	echo "use one of the two lines:"
	echo "dpkg-reconfigure tripwire ; tripwire -m p -Z low /etc/tripwire/twpol.txt"
	echo "twadmin -m F -S /etc/tripwire/site.key /etc/tripwire/twcfg.txt ; twadmin -m P -S /etc/tripwire/site.key /etc/tripwire/twpol.txt ; tripwire -m p -Z low /etc/tripwire/twpol.txt"
    fi
else
    echo "$FILE is not ready to be updated"
fi
