#! /bin/sh

##
## Usage: make_db [ -nostopserver ]
##  
## If called with the -noserver option, then the make_db script will
## not use remadmin to synchronize loading with a running whois_rip
## process.  This is useful for loading a database not in the
## rip.config file - as in testing a new mirror.
##

## Download flat files to $OBJDIR before !

DBDIR=/export/db

# Name of the configuration file
PROPERTIES=$DBDIR/conf/rip.config.load
# The database name for loading
DB=RIPE_load
# The source
SOURCE=RIPE
STOPSERVER=0

##############################################
# Directory layout

# Directory where the object files reside
OBJDIR=$DBDIR/tmp/load/${SOURCE}

# Filter that uses to convert files
FILTER=$DBDIR/scripts/mirror/ripe2rpsl

# Binary to unzip object files (snapshots)
UNZIP1='/usr/bin/gzip -cd'

# MySQL setup
SQLHOST=mysql
SQLPORT=3306
SQLUSER=dbuser
SQLPSWD=""
SQLROOTUSER=root
SQLROOTPSWD=""
SQLDATADIR=/var/mysql/data


# MySQL commands
# note: the "CMD" versions include appropriate starup options
MYSQL=/usr/local/mysql/bin/mysql
MYSQLCMD="$MYSQL -h$SQLHOST -P$SQLPORT -u$SQLUSER -p$SQLPSWD"
MYSQLADMIN=/usr/local/mysql/bin/mysqladmin
MYSQLADMINCMD="$MYSQLADMIN -h$SQLHOST -P$SQLPORT -u$SQLUSER -p$SQLPSWD"


log "Loading database started"


#set -x

# parse arguments, if any
for arg do
  case $arg in
    '-nostopserver')  
      STOPSERVER=0
      ;;
    *)
      error_exit "Usage: $0 [ -nostopserver ]\n" 
      exit 1
  esac
done

##############################################
# Update log
UPDLOG=/dev/null
HOST=$SQLHOST
USER=$SQLUSER
PASSWORD=$SQLPSWD

#
##############################################

echo
log "Creating working directory "
echo

# create working directory
mkdir -p $OBJDIR
if [ $? -ne 0 ]; then
  error_exit "Error creating working directory $OBJDIR, $0 exiting" 
fi

cd $OBJDIR 
if [ $? -ne 0 ]; then
   error_exit "Error changing to working directory $OBJDIR, $0 exiting"
fi

# The current serial
DEFCURRENTSERIAL=`cat ${OBJDIR}/${SOURCE}.CURRENTSERIAL`
DEFCURRENTSERIAL=${DEFCURRENTSERIAL:=1}
CURRENTSERIAL=${DEFSERIAL:=$DEFCURRENTSERIAL}

# List of object files (wildcards are allowed)
LIST=$OBJDIR/ripe.db.??.gz


export MYSQL HOST USER PASSWORD DB LOG LIST UNZIP1 FILTER PROPERTIES CURRENTSERIAL SOURCE


log "Loading the database [$SQLDATADIR/${DB}] [see list in ${UPDLOG}] "

$MYSQLADMINCMD flush-tables

######################### MYSQL LOADER ######
cd /export/db/utils/load && sh ./load_all.sh 2 # 2>${UPDLOG}

if [ $? -ne 0 ]; then
  error_exit "Error loading ${SOURCE} mirror, $0 exiting"
fi

$MYSQLADMINCMD flush-tables

log "Loading database finished witout errors"

