NAME="ripedb_ilines_update"
AUTHOR="Pim van Pelt"
MAILTO="pim@ipng.nl"
ESCALATE_MAILTO="pim@ipng.nl"
MASTERLOG="/home/ircd/cronscripts/logs/${NAME}.log"

PATH=/usr/local/bin:/usr/bin:/bin:/home/ircd/bin

INPUT_DELEGATED="/home/ircd/ircd/etc/ripedb/delegated-ripencc-latest"
OUTPUT_ROOT="/home/ircd/ircd/etc"
MANUAL_ASN_LIST="3303,12859" # Comma separated

do_country()
# $1=country $2=class $3=threshold
{
	delegated_ilines.py -i $INPUT_DELEGATED -o ilines.$1.$$ -c $1 -y $2
	[ ! -r ilines.$1.$$ ] && return -1
	[ `wc -l ilines.$1.$$ | awk '{ print $1 }'` -lt $3 ] && {
		warning "$1: File too short, less than $3 lines"
		rm -f -- ilines.$1.$$
		return -2
	}
	mv ilines.$1.$$ $OUTPUT_ROOT/include/ilines.$1.conf
	return 0
}

do_asn()
# $1=asn(s) $2=class $3=threshold
{
	asset_ilines.py -a '' -o ilines.asn.$$ -l $1 -y $2
	[ ! -r ilines.asn.$$ ] && return -1
	[ `wc -l ilines.asn.$$ | awk '{ print $1 }'` -lt $3 ] && {
		warning "$1: File too short, less than $3 lines"
		rm -f -- ilines.asn.$$
		return -2
	}
	mv ilines.asn.$$ $OUTPUT_ROOT/include/ilines.asn.conf
	return 0
}

do_asset()
# $1=as-set(s) $2=class $3=threshold
{
	asset_ilines.py -l '' -o ilines.as-set.$$ -a $1 -y $2
	[ ! -r ilines.as-set.$$ ] && return -1
	[ `wc -l ilines.as-set.$$ | awk '{ print $1 }'` -lt $3 ] && {
		warning "$1: File too short, less than $3 lines"
		rm -f -- ilines.as-set.$$
		return -2
	}
	mv ilines.as-set.$$ $OUTPUT_ROOT/include/ilines.as-set.conf
	return 0
}

function bitcron_main()
{
	cd $OUTPUT_ROOT || fatal "No OUTPUT_ROOT directory"

	echo "Gathering I-Lines for countries"
	do_country ch 200 1200 || error "ilines.ch.conf failed"
	do_country li 202 10 || error "ilines.li.conf failed"

	echo "Gathering I-Lines for AS numbers"
        ASN_LIST=$MANUAL_ASN_LIST
        [ -n "$ASN_LIST" ] && ASN_LIST=$ASN_LIST","
	ASN_LIST=$ASN_LIST$(awk -F'|' '$2=/(CH|LI)/ {
	    if ($3 == "asn") {
      		n++;
		if (n>1) { printf "," };
		printf $4
	    }
	  }' < $INPUT_DELEGATED )
	do_asn $ASN_LIST 250 1300 || error "ilines.asn.conf failed"

	echo "Gathering I-Lines for AS-SETs"
	do_asset AS-IP-MAN-PEERING-TIX,AS-IP-MAN-PEERING-CIXP,AS-IP-MAN-PEERING-SWISSIX 300 1300 || error "ilines.as-set.conf failed"

	if [ $ERR -eq 0 ]l; then
		echo "This is what we've got:"
		ls -l $OUTPUT_ROOT/include/ilines.*.conf
		tail -n 1 $OUTPUT_ROOT/include/ilines.*.conf

		echo "Committing to SVN"
		svn commit -m "Automatic I-lines update by ilines_update.cron"

		echo "HUPing ircd"
		pkill -HUP ircd
	else
		fatal "Not submitting/HUPing. This needs human attention"
	fi
}