#!/usr/bin/env bash

set -e

current_path=$PWD
scratch=$(mktemp -d -t tmp.XXXXXXXXXX)

# download export in tmp folder
# untar it
# build path for ttl file

# activate virtualenv

# call import rdf

# call import_hdabo_db -c

# call rebuild index

#       tarball="linux-${major}-${minor}-${patchlevel}.tar.bz2"
#      curl -q "http://kernel.org/path/to/$tarball" -o "$scratch/$tarball" || true

usage() { echo "Usage: $0 <virtualenv> <manage_path> <url>" 1>&2; exit 1; }


if [[ $# -ne 3 ]]; then
    echo "Illegal number of parameters"
    usage
fi


VIRTUALENV_PATH=$1
MANAGE_PATH=$2
RDF_URL=$3

curl -q "$RDF_URL" -o "$scratch/export.tar.gz"

cd "$scratch"
tar zxvf export.tar.gz

flist=( hda_data_* )

TTL_FILE=$PWD/${flist[0]}

cd "$MANAGE_PATH"

source "$VIRTUALENV_PATH/bin/activate"
export PYTHONPATH=$PWD
export LD_LIBRARY_PATH="$VIRTUALENV_PATH/lib"

python manage.py import_rdf "$TTL_FILE"
python manage.py import_hdabo_db -c
python manage.py rebuild_index -r --noinput


function finish {
  cd "$current_path"
  rm -rf "$scratch"
}

trap finish EXIT
