#!/bin/bash
# Build script for utsusemi package
# by Nobuo Okazaki
# Last modified on 2019-01-17
set -e
BASE=$(cd $(dirname $0)/../..; pwd)

PKGNAME=utsusemi
RPMBUILD=$BASE/rpmbuild
SRCPATH=$RPMBUILD/SOURCES
SPECPATH=$RPMBUILD/SPECS
DISTPATH=$BASE/dist
SRCDISTPATH=$BASE/dist/SPackages
RPMOPTS=(-ba --define "_topdir ${RPMBUILD}" --define "_sourcedir ${SRCPATH}" --define "debug_package %{nil}")

mkdir -p $RPMBUILD
mkdir -p $SRCPATH
mkdir -p $SPECPATH

# Build utsusemi
SPEC=$BASE/contrib/rpm/utsusemi.spec
cp -f $SPEC $SPECPATH
if [ -d $BASE/.git ]; then
  GITREF=$(cat $BASE/.git/HEAD | cut -d" " -f2)
  COMMIT=$(cat $BASE/.git/$GITREF | cut -b 1-8)
  BRANCH=$(echo $GITREF | cut -d/ -f3)
  GITTS=$(cat $BASE/.git/logs/$GITREF | cut -f1 | awk '{print $(NF-1)}')
  PKGDATE=$(date --date @$GITTS +%y%m%d)
else
  PKGDATE=$(date +%y%m%d)
  BRANCH=src
  COMMIT=00000000
fi

pushd $BASE > /dev/null
tar czf $SRCPATH/Utsusemi-$BRANCH.${PKGDATE}git${COMMIT}.tar.gz . \
  --transform='s#^\./#utsusemi/#' \
  --exclude=rpmbuild --exclude=.git
popd > /dev/null

rpmbuild "${RPMOPTS[@]}" $SPECPATH/utsusemi.spec

