#!/bin/bash

##
## Hourly cron job to make sure chains don't stay open for too long.
##
## Flush the chain from the timeslot before last to ensure that all
## slots are open for the minumum length of time
##

## Must have 2 args, 2nd must be numeric
if [ $# -ne 2 -o "${2#*[^0123456789]}" != "$2" ]
then
  echo Usage: $0 '<chain stub>' '<chain count>' >&1
  exit 1
fi

timeslot_length=$(( 24 / $2 ))

## This hour minus two time slots
##
## date +%k is the hour in 24hr format WITHOUT THE LEADING 0.
## Apparently, bash thinks 09 is octal and gets upset
##
## + 48 is just to make absolutely certain no -ve numbers occur,
## since these break mod (%)
flush_chain_time=$(( ( $(date +%k) - 2 * $timeslot_length + 48 ) % 24 ))

## Now we know what time we are pretending to be, work out which
## slot would be filled in that slot.
chain_num=$(( $flush_chain_time / $timeslot_length ))

chain=${1}-${chain_num}

echo Flushing chain $chain
ipchains -F $chain
