#!/bin/bash

# Available environment
# SRC_BASE = absolute path to cgcs-root 
# AVS_BASE = absolute path to AVS source
# CGCS_BASE = absolute path to CGCS source
# RPM_BUILD_BASE = Directory where the package .distro  directory can be found
# SRPM_OUT = Directory into which SRC RPMS are copied in preparation for mock build
# RPM_DIR = Directory into which binary RPMs are delivered by mock

SRC_DIR="/sources"
VERSION=$(grep '^Version:' PKG-INFO | awk -F ': ' '{print $2}' | sed -e 's/^[[:space:]]*//')
TAR_NAME=$(grep '^Name:' PKG-INFO | awk -F ': ' '{print $2}' | sed -e 's/^[[:space:]]*//')
CUR_DIR=`pwd`
BUILD_DIR=".distro/centos7/rpmbuild"

mkdir -p $BUILD_DIR/SRPMS

TAR="$TAR_NAME-$VERSION.tar.gz"
TAR_PATH="$BUILD_DIR/SOURCES/$TAR"

TAR_NEEDED=0
if [ -f $TAR_PATH ]; then
    n=`find . -cnewer $TAR_PATH -and !  -path './.git*' \
                                -and ! -path './build/*' \
                                -and ! -path './.pc/*' \
                                -and ! -path './patches/*' \
                                -and ! -path './.distro/*' \
                                -and ! -path './pbr-*.egg/*' \
                                | wc -l`
    if [ $n -gt 0 ]; then
        TAR_NEEDED=1
    fi
else
    TAR_NEEDED=1
fi

if [ $TAR_NEEDED -gt 0 ]; then
    tar czvf  $TAR_PATH .$SRC_DIR --exclude '.git*' --exclude 'build' --exclude='.pc' --exclude='patches' --exclude='.distro' --exclude='pbr-*.egg' --transform "s,^\.$SRC_DIR,$TAR_NAME-$VERSION,"
fi

for SPEC in `ls $BUILD_DIR/SPECS`; do
    SPEC_PATH="$BUILD_DIR/SPECS/$SPEC"
    RELEASE=$(grep '^Release:' $SPEC_PATH | awk -F ': ' '{print $2}' | sed -e 's/^[[:space:]]*//')
    NAME=`echo $SPEC | sed 's/.spec$//'`
    SRPM="$NAME-$VERSION-$RELEASE.src.rpm"
    SRPM_PATH="$BUILD_DIR/SRPMS/$SRPM"

    BUILD_NEEDED=0
    if [ -f $SRPM_PATH ]; then
        n=`find . -cnewer $SRPM_PATH | wc -l`
        if [ $n -gt 0 ]; then
            BUILD_NEEDED=1
        fi
    else
        BUILD_NEEDED=1
    fi

    if [ $BUILD_NEEDED -gt 0 ]; then
        rpmbuild -bs $SPEC_PATH --define="%_topdir $CUR_DIR/$BUILD_DIR" --define="_tis_dist .tis"
    fi
done