usage() { echo "Usage: $0 [-i <install_dir>] [-d <data_dir>]" 1>&2; exit 1; }

while getopts i:d: flag
do
    case "${flag}" in
        i) 
			INSTALL_DIR=${OPTARG}
			;;
        d) 
			DATA_DIR=${OPTARG}
			;;
		*)
            usage
            ;;
    esac
done

if [ -z "$INSTALL_DIR" ]
then
	INSTALL_DIR="$HOME"
fi

if [ -z "$DATA_DIR" ]
then
	DATA_DIR="$INSTALL_DIR/postgresql-11.14/data"
fi

echo "Installing Postgres at: $INSTALL_DIR";
echo "Postgres DATA Directory: $DATA_DIR";

cd $INSTALL_DIR
curl -LO https://ftp.postgresql.org/pub/source/v11.14/postgresql-11.14.tar.gz
tar -xvzf postgresql-11.14.tar.gz
cd postgresql-11.14/

./configure --prefix=$INSTALL_DIR/postgresql-11.14 --enable-cassert --enable-debug CFLAGS="-ggdb -Og -gdwarf-2 -g3 -std=c99"
error=$?
if [ $error -eq 0 ]; then
	make world
	make install-world

	errorMakeInstall=$?
	if [ $errorMakeInstall -eq 0 ]; then
		echo "Installed Successfully"
		echo "Creating DATA Directory at: $DATA_DIR";

		mkdir -p $DATA_DIR
		chown -R $(whoami) $DATA_DIR
		$INSTALL_DIR/postgresql-11.14/bin/initdb -D $DATA_DIR --no-locale
	else
		echo $errorMakeInstall
		echo "Build Failed: Error while installing postgresql-11.14"
		exit 1
	fi
else
	echo $error
	echo "Build Failed: Error while configuring postgresql-11.14"
	exit 1
fi
