#!/bin/bash

set -eu

tar=$1

version=$(echo "$1" | sed -n 's|.*cockpit-\([^ /-]\+\)\.tar\..*|\1|p')
if [ -z "$version" ]; then
    echo "make-srpm: couldn't parse version from tarball: $1"
    exit 2
fi

# We actually modify the spec so that the srpm is standalone buildable
modify_spec() {
sed -e "/^Version:.*/d" -e "1i\
%define wip wip\nVersion: $version\n"
}

tmpdir=$(mktemp -d $PWD/srpm-build.XXXXXX)
tar xaf "$1" -O cockpit-$version/tools/cockpit.spec | modify_spec > $tmpdir/cockpit.spec

rpmbuild -bs \
         --quiet \
         --define "_sourcedir $(dirname $1)" \
         --define "_specdir $tmpdir" \
         --define "_builddir $tmpdir" \
         --define "_srcrpmdir `pwd`" \
         --define "_rpmdir $tmpdir" \
         --define "_buildrootdir $tmpdir/.build" \
         $tmpdir/cockpit.spec

rpm --qf '%{Name}-%{Version}-%{Release}.src.rpm\n' -q --specfile $tmpdir/cockpit.spec | head -n1
rm -rf $tmpdir
