#!/bin/bash
set -e

SELFROOT=`dirname "$0"`
SELFROOT=`cd "$SELFROOT" && pwd`

PROJECT_DIR=
PASSENGER_DIR=
CONCURRENCY=1
EXTRA_ARGS=

function run()
{
  echo "$ $@"
  "$@"
}

function cleanup()
{
  set +e
  local pids=`jobs -p`
  if [[ "$pids" != "" ]]; then
    kill $pids >/dev/null 2>/dev/null
  fi
}

function usage()
{
  echo "Usage: ./jenkins_release [OPTIONS]"
  echo "Build RPMs and YUM repository. To be invoked from Jenkins."
  echo
  echo "Required options:"
  echo "  -p PATH         Path to a project"
  echo
  echo "Optional options:"
  echo "  -P PATH         Path to Phusion Passenger source directory"
  echo "  -j CONCURRENCY  Build concurrency (default: $CONCURRENCY)"
  echo "  -O ARG          Extra arguments to pass to build script"
}

function parse_options()
{
  local OPTIND=1
  local opt
  while getopts "p:P:j:O:h" opt; do
    case "$opt" in
    p)
      PROJECT_DIR="$OPTARG"
      ;;
    P)
      PASSENGER_DIR="$OPTARG"
      ;;
    j)
      CONCURRENCY="$OPTARG"
      ;;
    O)
      EXTRA_ARGS="$OPTARG"
      ;;
    h)
      usage
      exit
      ;;
    *)
      return 1
      ;;
    esac
  done

  if [[ "$PROJECT_DIR" = "" ]]; then
    echo "Please specify a project using -p."
    exit 1
  fi
}

parse_options "$@"

if [[ `whoami` != jenkins ]]; then
  echo "This script may only be run from Jenkins."
  exit 1
fi

echo "$ cd $SELFROOT"
cd "$SELFROOT"

BUILD_ARGS=(
  -p "$PROJECT_DIR"
  -j "$CONCURRENCY"
  -l
  $EXTRA_ARGS
)
if [[ "$PASSENGER_DIR" != "" ]]; then
  BUILD_ARGS+=(-P "$PASSENGER_DIR")
fi

run ./build "${BUILD_ARGS[@]}"
run ./repo_update \
  -p "$PROJECT_DIR" \
  -s auto-software-signing@phusion.nl \
  -x /etc/passenger_rpm_automation/signing_passphrase
