#! /bin/bash -ex

export TZ=UTC

copr_fe_url=https://copr.fedorainfracloud.org/coprs/g/pgjdbc/pgjdbc-travis/build
copr_be_link=https://copr-be.cloud.fedoraproject.org/results/@pgjdbc/pgjdbc-travis/fedora-rawhide-x86_64/
status_file=copr_build_id

test -z "$PARENT_VERSION" && exit 1
test -z "$PROJECT_VERSION" && exit 1
PROJECT_VERSION=${PROJECT_VERSION//-/_}

copr_wrapper ()
(
    set +x
    echo "running copr-cli wrapper"
    str="Created builds: "

    copr-cli "$@" 2>&1 | \
    while read line
    do
        echo "$line"
        case $line in
        "$str"*)
            echo "${line##$str}" > "$status_file"
            ;;
        esac
    done
)

set -o pipefail
cd "$1"
git_rev=$(git rev-parse --short=7 HEAD)
date_rev=$(date +%Y%m%d_%H%M%S)
release=${date_rev}.git$git_rev
sed -e "s!^Release:.*\$!Release: 1.$release%{?dist}!" \
    -e "s!^Version:.*\$!Version: $PROJECT_VERSION!" \
    -e "s!%global parent_ver.*!%global parent_ver $PARENT_VERSION!" \
    "$2".spec.tpl > "$2".spec

# See https://github.com/praiskup/srpm-tools
srpm-generator | tee stdout
srpm=$(grep Wrote: stdout | sed 's/^Wrote: //')

copr_wrapper --config "$1"/copr-token build --nowait @pgjdbc/pgjdbc-travis "$srpm"
copr_build_id=$(cat "$status_file")

concrete_copr_be_link=$copr_be_link$(printf "%08d" "$copr_build_id")-postgresql-jdbc/

set +x
echo "For build status, logs, etc. have a look at
$copr_fe_url/$copr_build_id/

Note that there might be multiple builds submitted, particularly if there copr
is configured to build for multiple versions of Fedora distribution.  For
concrete build results against latest Fedora version, have a look at:
$concrete_copr_be_link"

exit_cmd=:
while :
do
    status_output=$(copr --config "$1"/copr-token status "$copr_build_id")
    case $status_output in
        succeeded)
            break
            ;;
        failed)
            exit_cmd=false
            break
            ;;
        *)
            echo " * build $copr_build_id is in \"$status_output\" state [$(date)]"
            ;;
    esac
    sleep 30
done

echo " * getting the build log for rawhide chroot"
curl -L $concrete_copr_be_link/build.log.gz | gunzip || :

$exit_cmd
