#!/bin/bash -l

TARGET=target
PG_BUILD_OUT=$TARGET/build
PG_RUBY_PACKAGE_OUT=$TARGET/ruby_package
PROJECT_NAME="jam_db"

if [ -z $BUILD_NUMBER ]; then
    BUILD_NUMBER="1"
fi

VERSION="0.1.${BUILD_NUMBER}"

set -e

# remove the output directory
rm -rf $TARGET

mkdir -p $PG_BUILD_OUT
mkdir -p $PG_RUBY_PACKAGE_OUT

bundle install --path vendor/bundle

echo "building migrations"
bundle exec pg_migrate build --source . --out $PG_BUILD_OUT --test --verbose

echo "packaging migrations for ruby"bundle exec pg_migrate package --source $PG_BUILD_OUT --out $PG_RUBY_PACKAGE_OUT --name jam-db --version "$VERSION"
bundle exec pg_migrate package --source $PG_BUILD_OUT --out $PG_RUBY_PACKAGE_OUT --name $PROJECT_NAME --version $VERSION

if [ ! -z "$PACKAGE" ]; then
	bundle install --path target/vendor/bundle
	pushd target
		fpm -s gem -t deb ruby_package/jam_db-$VERSION.gem
		find vendor/bundle/ruby/2.2.0/cache -name '*.gem' | xargs -rn1 fpm -s gem -t deb
		find vendor/bundle/ruby/2.0.0/cache -name '*.gem' | xargs -rn1 fpm -s gem -t deb
	popd
fi
