#!/bin/bash

## VERSION:
#V#MakeRPM
#V#  version 1.0, copyright 2014, Jesse McClure
#V#  license: CC-BY-SA https://creativecommons.org/licenses/by-sa/2.0/
## HELP:
#H#
#H#makerpm will look in the current working directory for a spec file with
#H#the following requirements:
#H#
#H#1) The "source" line should provide a full git url from which the source
#H#can be cloned
#H#
#H#2) The "version" line should provide only a base number upon which the
#H#commit count will be appended
#H#
#H#The upstream git source must also include a Makefile in the toplevel
#H#directory with a directive called 'dist' which will make a source
#H#tarball (.tar.gz) in that same directory.
#H#
#H#makerpm will 1) revise the source and version lines in a copy placed in
#H#rpmbuild's topdir/SPECS/ folder, 2) install the build dependencies if it
#H#is the first build for the package on the machine, 3) obtain the git
#H#source, 4) make the tarball and move it to topdir/SOURCES/, 5) build the
#H#rpm and srpm, and 6) clean up/remove the cloned git dir.


if [[ -n $1 ]]; then
	case $1 in
		-h|--help|help) awk '/^#[VH]#/ { sub(/^#[VH]#/,""); print $0; }' $0 ;;
		-v|--ver*|ver*) awk '/^#V#/ { sub(/^#V#/,""); print $0; }' $0 ;;
	esac
	exit
fi

start_dir=$(pwd)

## CHECK FOR SPEC FILE:
spec=$(find -name "*.spec")
if [[ ! -f ${spec} ]]; then
	echo "No spec file found"
	return
fi

## GET VALUES FROM SPEC FILE:
pkgname=$(awk '/^name:/ { print $2; }' ${spec})
git_url=$(awk '/^source:/ { print $2; }' ${spec})
pkgver_base=$(awk '/^version:/ { print $2; }' ${spec})

## CHECK BUILD ENVIRONMENT:
topdir=$(rpmbuild --eval '%_topdir')
mkdir -p ${topdir}/{BUILD,RPMS,SOURCES,SPECS,SRPMS}

## INSTALL BUILD DEPS IF FIRST BUILD:
builds=$(find ${topdir}/RPMS/ -name "${pkgname}*")
[[ -z $builds ]] && sudo yum-builddep ${spec}

## GET CODE AND MAKE SOURCE TARBALL:
git clone ${git_url}
cd ${pkgname}
pkgver="${pkgver_base}.$(git rev-list --count HEAD)"
make dist
mv ./${pkgname}*.tar.gz ${topdir}/SOURCES/${pkgname}-${pkgver}.tar.gz

## PREPARE REAL SPEC FILE:
cd ${start_dir}
cp ${spec} ${topdir}/SPECS/
cd ${topdir}/SPECS/
sed -i 's/^version: .*$/version: '${pkgver}'/' ${pkgname}.spec
sed -i 's/^source: .*$/source: '${pkgname}-${pkgver}'.tar.gz/' ${pkgname}.spec

## RUN RPMBUILD:
cd ${topdir}/SPECS
rpmbuild -ba ${pkgname}.spec

## CLEAN UP:
cd ${startdir}
rm -rf ${pkgname}