#!/bin/bash
set -e

# See README for more information

# The working directory. Resulting tarball will be placed in the directory above.
PKG_DIR=/tmp/flys-importer
# Path to oracle zip archives and an oracle_cx rpm
ORACLE=/path/to/oracle/archives
# Default conf
CONF_DIR=/path/to/conf/dir
# Path to the flys checkout
FLYS_DIR=/path/to/flys/root
# Extra packages
EXTRAS=/path/to/gdal

rm -fr $PKG_DIR
mkdir -p $PKG_DIR/hydr_morph
mkdir -p $PKG_DIR/geodaesie
mkdir -p $PKG_DIR/opt/lib64
mkdir -p $PKG_DIR/schema

cd ${FLYS_DIR}/flys-backend
mvn -f pom-oracle.xml clean compile assembly:single
cp target/flys-backend-1.0-SNAPSHOT-jar-with-dependencies.jar \
    $PKG_DIR/hydr_morph/importer.jar
cp ${FLYS_DIR}/flys-backend/contrib/shpimporter/*.py $PKG_DIR/geodaesie
cp ${FLYS_DIR}/flys-backend/contrib/run_geo.sh \
    ${FLYS_DIR}/flys-backend/contrib/run_hydr_morph.sh \
    $PKG_DIR
cp -r ${CONF_DIR} $PKG_DIR
ln -s /usr/lib64/libproj.so.0.6.6 $PKG_DIR/opt/lib64/libproj.so # workaround for bad packaging
rm -rf /tmp/other_rpms
mkdir /tmp/other_rpms
cd /tmp/other_rpms

rpm2cpio ${EXTRAS}/libgdal1-1.9.0-intevation1.x86\_64.rpm | cpio -i --make-directories
rpm2cpio ${EXTRAS}/gdal-1.9.0-intevation1.x86\_64.rpm | cpio -i --make-directories
rpm2cpio ${EXTRAS}/python-gdal-1.9.0-intevation1.x86\_64.rpm | cpio -i --make-directories
rpm2cpio ${ORACLE}/cx\_Oracle-5.1.2-11g-py26-1.x86\_64.rpm | cpio -i --make-directories
cp -r /tmp/other_rpms/usr/* $PKG_DIR/opt
rm -rf /tmp/other_rpms

cp ${FLYS_DIR}/flys-backend/doc/schema/*.sql $PKG_DIR/schema
cp ${FLYS_DIR}/flys-backend/doc/documentation/de/importer-manual.pdf $PKG_DIR

# Oracle (Do not distribute)
unzip ${ORACLE}/instantclient-basic-linux-x86-64-11.2.0.2.0.zip -d $PKG_DIR//opt
unzip ${ORACLE}/instantclient-sdk-linux-x86-64-11.2.0.2.0.zip -d $PKG_DIR//opt
unzip ${ORACLE}/instantclient-sqlplus-linux-x86-64-11.2.0.2.0.zip -d $PKG_DIR//opt

mkdir $PKG_DIR//opt/instantclient_11_2/lib
cd $PKG_DIR//opt/instantclient_11_2/lib
ln -s ../libclntsh.so.11.1 .
ln -s ../libclntsh.so.11.1 libclntsh.so
ln -s ../libnnz11.so .
ln -s ../libocci.so.11.1 .
ln -s ../libocci.so.11.1 libocci.so
ln -s ../libociei.so .
ln -s ../libocijdbc11.so .
ln -s ../libsqlplusic.so .
ln -s ../libsqlplus.so .
# End Oracle

sed -i 's/shpimporter\/shp/geodaesie\/shp/' $PKG_DIR/run_geo.sh

cd $PKG_DIR/..
DATE=$(date +%Y%m%d%H%m)
tar -czf flys-importer${DATE}.tar.gz flys-importer
sha1sum flys-importer${DATE}.tar.gz > flys-importer${DATE}.tar.gz.sha1
