#!/bin/bash

COPR="mvadkert/beakerlib-libraries"
COPR_URL="https://copr.fedorainfracloud.org/"

usage() {
    cat << EOF
Usage: $0

Build beakerlib libraries via '${COPR_URL}'
in repository '${COPR}'.
EOF
    exit 0
}

info() {
    echo "::: $@"
}

exit_error() {
    echo "error: $@"
    exit 1
}

[ "$1" = "-h" -o "$1" == "--help" ] && usage

spec="beakerlib-libraries.spec"

read ver rel <<< $(git describe --tags | sed 's/\([^-]*\)-\(.*\)/\1 \2/') || exit_error \
    "could not get version/release from 'git describe --tags'"
[ -z "$rel" ] && rel=1
rel=$(echo $rel | tr '-' '.')

# sanity
[ -z "$ver" ] && exit_error "could not get version from 'git describe --tags'"
rpm -q rpm-build &>/dev/null || exit_error "rpmbuild not installed"
rpm -q copr-cli &>/dev/null || exit_error "copr-cli not installed"
copr list &>/dev/null || exit_error "copr-cli not configured"

# create folders required for building
mkdir -p $HOME/rpmbuild/SOURCES
mkdir -p $HOME/rpmbuild/SPECS
mkdir -p $HOME/rpmbuild/BUILD

spec_broot="$HOME/rpmbuild/SPECS/$(basename $spec)"

info "copying spec file '$spec' to '$HOME/rpmbuild/SPECS'"
cp $spec $HOME/rpmbuild/SPECS

info "setting version and release to ${ver}-$rel"
sed -i "s/VERSION/$ver/" $spec_broot
sed -i "s/RELEASE/$rel/" $spec_broot

info "adding legacy Library path before creating the source archive"

TEMPDIR=`mktemp -d`
# Only create package from master brach
git checkout -q master
git checkout-index -a -f --prefix="$TEMPDIR/"
pushd "$TEMPDIR"
for LIB in $(find */* -maxdepth 0 -type d); do
    COMPONENT=${LIB///*}
    LIBNAME=${LIB##*/}
    mkdir -p ".temp/beakerlib-libraries/$COMPONENT/Library/$LIBNAME"
    cp -rf "$LIB"/* ".temp/beakerlib-libraries/$COMPONENT/Library/$LIBNAME"
    info "+ $LIB"
done

info "creating source tarball to '$HOME/rpmbuild/SOURCES'"
tar -C .temp -cz -f $HOME/rpmbuild/SOURCES/beakerlib-libraries.tar.gz .

info "creating src.rpm via 'rpmbuild -bs'"
SRCRPM=$(rpmbuild -bs $spec_broot | tee /dev/tty | awk '{print $2}')

info "removing temporary directory"
popd
rm -rf "$TEMPDIR"
git checkout -q -

[ -f "$SRCRPM" ] || exit_error "could not build src.rpm"

info "trying to rebuild '$(basename $SRCRPM)' via 'rpmbuild --rebuild' (sanity check)"
rpmbuild --rebuild $SRCRPM --quiet || exit_error "could not rebuild src.rpm"

info "submitting to copr (waiting can be safely interrupted)"
copr build "$COPR" $SRCRPM
