#!/usr/bin/env bash

[[ "$0" == /* ]] && typeset -r PRG=$0 || typeset -r PRG=$PWD/$0

BINDIR=$(dirname "$PRG")
typeset -r BINDIR
source "${BINDIR}/lib/logging.sh"


W3M=/opt/homebrew/bin/w3m
AWK=/usr/bin/awk
CURL=/usr/bin/curl

source "${BINDIR}/lib/logging.sh"
TARGET="${1-11.4.88.0.1.207.1}"
hg_branch="s11u4_sust_087"
log::info "TARGET:${TARGET}"

URL="http://grt.us.oracle.com/grt/webservice/grtList/?gate=240&show=All&gateName=S11.4-SRU&status=4&target=${TARGET}"
log::debug $URL

output=$(/opt/homebrew/bin/w3m "$URL" -M -cols 400 -graph -dump 2>&1)

out=$(echo "$output" | $AWK '/^Details/ {found=1; next} found && NF')

if [[ -z "$out" ]];
then
	log::info "There are no queued RTIs for \"${TARGET}\". Nothing to do..."
	exit 0
fi


log::info "Starting build for for Ul11u4SRU"
log::info "Target: \"${TARGET}\""

JENKINS_TOKEN='1154eb0158729a7d326c1db13e7dca0cea'
JENKINS_SERVER='http://mrshughes.us.oracle.com/jenkins/'

JOB_URL="${JENKINS_SERVER}/job/Solaris_11/job/11.4/job/userland-sru/job/userland-sru-build-11.4/buildWithParameters"

log::info "Using '${JOB_URL}'"

set -x
curl -X POST "${JOB_URL}" \
	--user "pnyc:${JENKINS_TOKEN}" \
	--data-urlencode "Build_Label=${TARGET}" \
	--data-urlencode "hg_branch=${hg_branch}" \
	--data-urlencode "hguser=petr.nyc@oracle.com" \
	--data-urlencode "verbose=true" \
	--data-urlencode "debug=true" \
	--data-urlencode "scriptdir=./solaris/userland/sru/" \
	--data-urlencode "do_check_sru_cbe=true" \
	--data-urlencode "prepare_work_area=true" \
	--data-urlencode "do_build=true" \
	--data-urlencode "merge_repo=true" \
	--data-urlencode "create_sparse_repo=true" \
	--data-urlencode "check_incorporations=true" \
	--data-urlencode "zip_sparse_repo=true" \
	--data-urlencode "create_escrow=true" \
	--data-urlencode "create_foss=true" \
	--data-urlencode "integration_dryrun=false" \
	--data-urlencode "confirm_before_ingegration=false" \
	--data-urlencode "wait_for_dock_open=true" \
	--data-urlencode "delivery=true"

log::info "The job will be started here:"
log::info "    ${JOB_URL%%buildWith*}"
