#!/bin/bash

if [ ! -f "$1" ]; then
  echo "Usage: $0 <absolute path to TSCO 20.02 installer tar.gz file>"
  exit 1
fi

SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"

if ! command -v tar &> /dev/null
then
    echo "tar could not be found"
    exit 1
fi

if ! command -v unzip &> /dev/null
then
    echo "unzip could not be found"
    exit 1
fi

if ! command -v zip &> /dev/null
then
    echo "zip could not be found"
    exit 1
fi

if ! command -v sed &> /dev/null
then
    echo "sed could not be found"
    exit 1
fi

if [ -f "$1" ]; then 
    echo "Extracting installer file '$1' into directory $SCRIPTPATH"
    if [ -d "BCO" ]; then
		rm -fr BCO
	fi
	
	tar xvzf $1 -C . > /dev/null 2>&1
	
	cd BCO/Disk1/files/bco/
    if [ -d "databaseschema" ]; then
		rm -fr databaseschema
	fi	
	
	unzip databaseschema.zip > /dev/null 2>&1
	
	echo "Patching $SCRIPTPATH/BCO/Disk1/files/bco/databaseschema/postgres/install/sequences_alignment.sql"
	
	sed -i 's/sequence_name) into/sequence_name::varchar) into/' databaseschema/postgres/install/sequences_alignment.sql
	
	rm -fr databaseschema.zip
	
	zip -r databaseschema.zip databaseschema/ > /dev/null 2>&1
	
	rm -fr databaseschema/
	
	cd $SCRIPTPATH
	
	echo "Installer patched and ready to be executed at $SCRIPTPATH/BCO/Disk1"
	
    exit 0
else
    echo "Archive file '$1' does not exist."
    exit 1
fi

