#!/bin/bash
# Build script for manyo-deps and manyo packages
# by Nobuo Okazaki
# Last modified on 2021-03-03
set -e
BASE=$(cd $(dirname $0); pwd)

MODE=$1
SRCBASE=$2

PKGNAME=manyo
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}")

if [ -z "$MODE" ]; then
  echo "Usage: $0 {mxml|deps|manyo}"
  exit 1
fi

echo "Basepath: $BASE"
echo "RPMBUILD: $RPMBUILD"
echo

set -x

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

if [ "$MODE" == "mxml" ]; then
  # Build mxml-2.9
  cp -f $BASE/manyo-deps-mxml-2.9.spec $SPECPATH
  pushd $SRCPATH > /dev/null
    wget https://kojipkgs.fedoraproject.org/packages/mxml/2.9/1.el7/src/mxml-2.9-1.el7.src.rpm -O mxml-2.9-1.el7.src.rpm
    rpm2cpio mxml-2.9-1.el7.src.rpm | cpio -idmv
  popd
  rpmbuild "${RPMOPTS[@]}" $SPECPATH/manyo-deps-mxml-2.9.spec
fi
  
if [ "$MODE" == "deps" ]; then
  # Build nexus and python-matplotlib
  cp -f $BASE/*.spec $SPECPATH
#  wget https://github.com/nexusformat/code/releases/download/4.3.1/nexus-4.3.1.tar.gz -O $SRCPATH/nexus-4.3.1.tar.gz
  wget https://github.com/nexusformat/code/archive/v4.4.3.tar.gz -O $SRCPATH/nexus-4.4.3.tar.gz
#  pushd $SRCPATH > /dev/null
#    yumdownloader --source python-matplotlib-1.2.0-16.el7
#    rpm2cpio python-matplotlib-1.2.0-16.el7.src.rpm | cpio -idmv
#  popd
  rpmbuild "${RPMOPTS[@]}" $SPECPATH/manyo-deps-nexus-4.4.3.spec
#  rpmbuild "${RPMOPTS[@]}" $SPECPATH/manyo-deps-python-matplotlib-1.2.0-16.spec
  echo
  echo
  echo '******************************************************************'
  echo  manyo-deps-mxml, manyo-deps-nexus and manyo-deps-python-matplotlib
  echo  have been built.
  echo  Now ready to build manyo package after installation them.
  echo  Packages located at $RPMBUILD/RPMS/x86_64
  echo '******************************************************************'
  exit 0
fi

if [ "$MODE" == "manyo" ]; then
  # Build manyo
  SPEC=$BASE/manyo.spec
  GITDIR=$SRCBASE/.git
  cp -f $SPEC $SPECPATH
  cp -f $BASE/manyo-*.patch $SRCPATH
  if [ -d $GITDIR ]; then
    GITREF=$(cat $GITDIR/HEAD | cut -d" " -f2)
    COMMIT=$(cat $GITDIR/$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)
    PKGDATE=$(date -d "$(git log --date=iso --pretty=format:"%ad" -1 | cut -d" " -f1-2)" +%y%m%d)
  else
    PKGDATE=$(date +%y%m%d)
    BRANCH=src
    COMMIT=00000000
  fi

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

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

