#!/bin/sh
# Copyright © 2013 Filippo Giunchedi <filippo@debian.org>
# Copyright © 2014 Luciano Bello <luciano@debian.org>
# This work is free. You can redistribute it and/or modify it under the
# terms of the Do What The Fuck You Want To Public License, Version 2,
# as published by Sam Hocevar.
# See the LICENSE file for more details.

BASEDIR=${BASEDIR:-/var/lib/ieee-data/}
RUN_PARSERS=${RUN_PARSERS:-1}
OLD="5"
FORCE=false
QUIET=false

set -e

ouiurl="http://standards.ieee.org/regauth/oui/oui.txt"
iaburl="http://standards.ieee.org/regauth/oui/iab.txt"
tmpf=$(tempfile)

Die () {
	$QUIET || echo $1 
	exit 1
}

testFileOUI () {
LOOKOUI='OUI/MA-L\s*Organization\s*company_id\s*Organization\s*Address'
head -n 6 $1 | tr -d '\n' | grep -qe "$LOOKOUI" || ( rm $1 && Die "The downloaded oui.txt looks corrupted." )
}

testFileIAB () {
LOOKIAB='OUI\s*Organization\s*IAB\sRange\s*Organization\s*Address'
head -n 6 $1 | tr -d '\n' | grep -qe "$LOOKIAB" || ( rm $1 && Die "The downloaded iab.txt looks corrupted." )
}

while getopts ":fq" opt; do
  case $opt in
    f)
      FORCE=true
      ;;
    q)
      QUIET=true
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      ;;
  esac
done

dler=""
[ -x $(which curl) ] && dler="curl"
[ -x $(which lwp-request) ] && dler="lwp-request -m GET"
[ -x $(which wget) ] && dler="wget -q -O-"

if [ -z "$dler" ]; then
	Die "Unable to find a suitable downloader, please install wget or curl or libwww-perl"
fi

cd $BASEDIR || { Die "can't cd to $BASEDIR"; }

LASTUPDATE=$(cat $BASEDIR/.lastupdate)
OLD_SECONDS=$(expr $OLD \* 86400)
CURRENT=$(date +%s)
AGE=$(expr $CURRENT - $LASTUPDATE)

if [ $FORCE = false -a $AGE -le $OLD_SECONDS ]; then
	Die "The files are kinda new yet (less than $OLD days old)"
fi

$QUIET || echo "Downloading $ouiurl to $BASEDIR/oui.txt"
$dler $ouiurl > $tmpf || { Die "$dler $iaburl exit with $?"; }
testFileOUI $tmpf
mv $tmpf oui.txt

$QUIET || echo "Downloading $iaburl to $BASEDIR/iab.txt"
$dler $iaburl > $tmpf || { Die "$dler $iaburl exit with $?";}
testFileIAB $tmpf
mv $tmpf iab.txt

if [ -x $(which run-parts) ] && [ -d update.d ] && [ $RUN_PARSERS -ne 0 ]; then
	$QUIET || echo "Running parsers from $BASEDIR/update.d"
	run-parts -a "$BASEDIR" -a oui.txt update.d/
	run-parts -a "$BASEDIR" -a iab.txt update.d/
fi
