#!/bin/bash
# text formatting
YELLOW="\033[1;33m"
CYAN="\033[1;96m"
MAGENTA="\033[1;35m"
GREEN="\033[1;32m"
RED="\033[1;31m"
BLUE="\033[1;34m"
DEFCOLOR="\033[0m"
bold=$(tput bold)
normal=$(tput sgr0)


########## SET THIS ################

RPM_BUILD_ROOT="$HOME/rpmbuild"
RPM_BIN_ROOT="$HOME/Quimup/Release"
RPM_SPEC_ROOT="./rpm"
RPM_SHARE_ROOT="./share"

####################################


# check if rpmbuild is installed:
SERVICE=`which rpmbuild &> /dev/null`
if [[ $? != 0 ]];
then
echo -e $RED"Please install rpmbuild before using this script"$DEFCOLOR
read -n 1 -s -r -p "Press any key to exit"
echo
exit 0
fi

echo
echo "This script will create $RPM_BUILD_ROOT with sub-dirs"
echo "The spec file will be copied from $RPM_SPEC_ROOT"
echo "The spec file will copy the binary from $RPM_BIN_ROOT"
echo "The spec file will copy 'share' from $RPM_SHARE_ROOT"
echo "The rpm will be built from $RPM_BUILD_ROOT/SPECS as follows:"
echo -e $bold"rpmbuild --target x86_64 -bb quimup_fedora.spec"$normal
echo "The created .rpm will be copied here"
echo "Finally $RPM_BUILD_ROOT will be removed"
echo
echo -e $YELLOW"RPM_BUILD_ROOT = $RPM_BUILD_ROOT"$DEFCOLOR
echo -e $YELLOW"RPM_BIN_ROOT   = $RPM_BIN_ROOT"$DEFCOLOR
echo -e $YELLOW"RPM_SPEC_ROOT  = $RPM_SPEC_ROOT"$DEFCOLOR
echo -e $YELLOW"RPM_SHARE_ROOT = $RPM_SHARE_ROOT"$DEFCOLOR


echo
read -n 1 -s -r -p "Press any key to continue"
echo

echo "Setting up $RPM_BUILD_ROOT"
mkdir $RPM_BUILD_ROOT
mkdir $RPM_BUILD_ROOT/BIN
mkdir $RPM_BUILD_ROOT/SHARE
#mkdir $RPM_BUILD_ROOT/BUILD
mkdir $RPM_BUILD_ROOT/RPMS
mkdir $RPM_BUILD_ROOT/RPMS/x86_64
#mkdir $RPM_BUILD_ROOT/RSOURCES
mkdir $RPM_BUILD_ROOT/SPECS
#mkdir $RPM_BUILD_ROOT/SRPMS

echo -e $BLUE"Copying binary to build directory"$DEFCOLOR
cp $RPM_BIN_ROOT/quimup $RPM_BUILD_ROOT/BIN

echo -e $BLUE"Stripping binary"$DEFCOLOR
strip $RPM_BUILD_ROOT/BIN/quimup

echo -e $BLUE"Copying spec file to build directory"$DEFCOLOR
cp $RPM_SPEC_ROOT/quimup_fedora.spec $RPM_BUILD_ROOT/SPECS/

echo -e $BLUE"Copying share dir to build directory"$DEFCOLOR
cp -r $RPM_SHARE_ROOT/* $RPM_BUILD_ROOT/SHARE/

echo -e $BLUE"Compressing manual page"$DEFCOLOR
gzip -9 -n $RPM_BUILD_ROOT/SHARE/man/man1/quimup.1

#echo -e $BLUE"Changing ownership of $RPM_BUILD_ROOT/SHARE to root"$DEFCOLOR
#sudo chown -R root $RPM_BUILD_ROOT/SHARE
#sudo chgrp -R root $RPM_BUILD_ROOT/SHARE

STARTDIR=$PWD
echo -e $BLUE"Moving to $RPM_BUILD_ROOT/SPECS"$DEFCOLOR
cd $RPM_BUILD_ROOT/SPECS/

echo -e $BLUE"Running 'rpmbuild --target x86_64 -bb quimup_fedora.spec'"$DEFCOLOR
rpmbuild --target x86_64 -bb quimup_fedora.spec

echo -e $BLUE"Moving back to $STARTDIR"$DEFCOLOR
cd $STARTDIR

echo -e $BLUE"Copyin rpm to here"$DEFCOLOR
cp $RPM_BUILD_ROOT/RPMS/x86_64/quimup*.rpm $STARTDIR/

echo -e $BLUE"removing $RPM_BUILD_ROOT"$DEFCOLOR
rm -r $RPM_BUILD_ROOT

echo
read -n 1 -s -r -p "Press any key to exit"
echo
exit 0
