#!/bin/bash
RPMBASE=$(pwd)/tmp-rpmbuild.$$
CONTAINER=builder

TARGET=$1
SPEC=$2

rm -rf $RPMBASE
mkdir -p $RPMBASE/{SOURCES,SPECS}
cp -av $TARGET/* $RPMBASE/SOURCES
cp -av $TARGET/$SPEC $RPMBASE/SPECS

while read src; do
  if [ -n "$src" ]; then
    wget -O $RPMBASE/SOURCES/$src https://download.mlf.io/pub/utsusemi4/sources/$src
  fi
done < $TARGET/sources.txt

mkdir -p dist
docker run --rm --name builder.$$ \
  -v $(pwd)/dist:/tmp/dist \
  -v $RPMBASE:/home/builder/rpmbuild \
  --user 1000:1000 \
  $CONTAINER \
  -c "sudo yum -y install /tmp/dist/*.{x86_64,noarch}.rpm; sudo yum-builddep -y rpmbuild/SPECS/$SPEC && rpmbuild -ba rpmbuild/SPECS/$SPEC"
cp -av $RPMBASE/RPMS/{x86_64,noarch}/* dist
cp -av $RPMBASE/SRPMS/* dist
rm -rf $RPMBASE
