#!/bin/bash
YEAR=`date "+%Y"`
MONTH=`date "+%m"`
PWDIR=/var/pwhois
COMP='/bin/bzip2 -fq '
DECOMP=/bin/gunzip
DL='/usr/bin/wget -q'
RELOAD=0

# Parse command line parameters
while [ $# -gt 0 ]
do
    case "$1" in
        -r)  RELOAD=1;;
	-*)
            echo >&2 "usage: $0 [-r]"
	    exit 1;;
	*)  break;;	# terminate while loop
    esac
    shift
done

# Download latest file
cd $PWDIR
# not working

while [[ ! "$yn" == "Y" ]]
do
echo "You must download the file manually and save to '$PWDIR/lacnic.db.gz'";
echo "Are you ready to continue with decompress? (Y,N) ";
read yn 
done

$DECOMP $PWDIR/lacnic.db.gz

# Reload import latest data using pwhois-updatedb if user wants
# and if file size is nonzero 
if [[ $RELOAD -gt 0 && -s $PWDIR/lacnic.db ]]; then
   /usr/local/sbin/pwhois-updatedb -v -i $PWDIR/lacnic.db -v --import-rpsl2-dump --registry-xml /var/pwhois/ipv4-address-space.xml -l /var/log/pwhois-updatedb.log
fi


# Always keep compressed last copy around in case the transfer fails 
# This also removes the existing file after compression
if [[ -r $PWDIR/lacnic.db && -s $PWDIR/lacnic.db ]]; then
   mv $PWDIR/lacnic.db $PWDIR/former.lacnic.db;
   $COMP $PWDIR/former.lacnic.db
fi

       # Remove older temporary files if they exist (not needed)
if [ -f $PWDIR/lacnic.db* ]; then
   rm -f $PWDIR/lacnic.db*;
fi
