##
## Obtain various platform information
##

OS=`uname`
if [ "${OS}" != "Linux" ] ; then
	printf "'$0' is ONLY available on '${OS}'!\n"
	exit 255
fi

if [ -f "/etc/redhat-release" ] ; then
	DISTRIBUTION=`cat /etc/redhat-release | cut -c1-7`
	DIST_VERSION=`cat /etc/redhat-release | tr -d [:alpha:][:blank:][\(\)]`
	if [ "${DISTRIBUTION}" = "Fedora " ] ; then
		MESSAGE="[built for Fedora ${DIST_VERSION}]"
	elif [ "${DISTRIBUTION}" = "CentOS " ] ; then
		MESSAGE="[built for CentOS ${DIST_VERSION}]"
	elif [ "${DISTRIBUTION}" = "Red Hat" ] ; then
		MESSAGE="[built for Red Hat ${DIST_VERSION}]"
	else
		printf "'$0' is ONLY available on 'Fedora', 'CentOS', or "
		printf "'Red Hat' distributions!\n"
		exit 255
	fi
else
	printf "'$0' is ONLY available on 'Fedora', 'CentOS', or "
	printf "'Red Hat' distributions!\n"
	exit 255
fi


##
## Establish various shared variables
##

PKI_DIR="pki"
export PKI_DIR

PKI_BASE_DIR="${PKI_DIR}/base"
export PKI_BASE_DIR

PKI_DOGTAG_DIR="${PKI_DIR}/dogtag"
export PKI_DOGTAG_DIR

PKI_REDHAT_DIR="${PKI_DIR}/redhat"
export PKI_REDHAT_DIR

PKI_CMAKE_DIR="cmake"
export PKI_CMAKE_DIR

PKI_BASE_MANIFEST="CMakeLists.txt"
export PKI_BASE_MANIFEST

PKI_DOGTAG_MANIFEST="CMakeLists.txt"
export PKI_DOGTAG_MANIFEST

PKI_REDHAT_MANIFEST="CMakeLists.txt"
export PKI_REDHAT_MANIFEST

RHEL="/rhel/"

##
## Usage statement
##

Usage()
{
	printf "\n"
	printf "Usage:  $0 [options] <target>\n\n"
	printf "        where <target> is one of the following:\n\n"
	printf "            srpm         - copies a spec file from local source,\n"
	printf "                           generates a tarball from local source,\n"
	printf "                           and produces an SRPM\n"
	printf "                           [suitable for use by 'mock']\n\n"
	printf "            rpms         - copies a spec file from local source,\n"
	printf "                           generates a tarball from local source,\n"
	printf "                           and produces an SRPM and one or more RPMS\n"
	printf "                           ${MESSAGE}\n\n"
	printf "Options:\n"
	printf "      --without-test       Do not run unit tests\n\n"
	printf "      --without-server     Do not build server packages\n\n"
	printf "      --without-javadoc    Do not build Javadoc package\n\n"
	printf "      --without-debug      Do not build debug packages\n\n"
	printf "      --createrepo=<file>  Create a repository\n"
	printf "                           with the rpms built.\n"
	printf "                           Provide the configuration\n"
	printf "                           file with the details.\n\n"
	printf "  -v, --verbose            Run in verbose mode\n\n"
}


##
## Compute build options
##
##
##      Examples:
##
##          # script -c "pki/scripts/compose_dogtag_pki_meta_packages rpms"
##          # ls packages/SRPMS
##          dogtag-pki-10.5.0-0.0.fc27.src.rpm
##
##          # script -c "USE_TIMESTAMP=1 USE_GIT_COMMIT_ID=1
##            pki/scripts/compose_dogtag_pki_meta_packages rpms"
##          # ls packages/SRPMS
##          dogtag-pki-10.5.0-0.0.20170829113604.6d23ffdd.fc27.src.rpm
##
##          # script -c "USE_TIMESTAMP=0 USE_GIT_COMMIT_ID=0
##            pki/scripts/compose_dogtag_pki_meta_packages rpms"
##          # ls packages/SRPMS
##          dogtag-pki-10.5.0-0.0.fc27.src.rpm
##
##          # script -c "USE_TIMESTAMP=1 USE_GIT_COMMIT_ID=0
##            pki/scripts/compose_dogtag_pki_meta_packages rpms"
##          # ls packages/SRPMS
##          dogtag-pki-10.5.0-0.0.20170829113859.fc27.src.rpm
##
##          # script -c "USE_TIMESTAMP=0 USE_GIT_COMMIT_ID=1
##            pki/scripts/compose_dogtag_pki_meta_packages rpms"
##          # ls packages/SRPMS
##          dogtag-pki-10.5.0-0.0.6d23ffdd.fc27.src.rpm
##

compute_build_options()
{
	# Optionally compute a timestamp
	if [ -n ${USE_TIMESTAMP} ] && [ "${USE_TIMESTAMP}" = "1" ]; then
		TIMESTAMP=`date +"%Y%m%d%H%M%S"`
		echo "TIMESTAMP: ${TIMESTAMP}"
		_TIMESTAMP=`printf ".%.14s" ${TIMESTAMP}`
		OPTIONS+=(--define "_timestamp ${_TIMESTAMP}")
	fi

	# Optionally fetch the git commit ID from the source repository
	if [ -n ${USE_GIT_COMMIT_ID} ] && [ "${USE_GIT_COMMIT_ID}" = "1" ]; then
		COMMIT_ID=`git -C "${PKI_DIR}" rev-parse --short=8 HEAD`
		echo "COMMIT_ID: ${COMMIT_ID}"
		_COMMIT_ID=`printf ".%.8s" ${COMMIT_ID}`
		OPTIONS+=(--define "_commit_id ${_COMMIT_ID}")
	fi
}


###
#   Create repository using the details in the config file ###
#   Function parameters - $1 - repository file path.
###

Create_repo_after_build()
{
	if [ $# -eq 0 ]; then
             echo "No repository configuration provided. Cannot create a repo."
             exit -1
	fi

	if [ ! -f $1 ]; then
             echo "$1 does not exist."
             exit -1
	fi

	. $1

	### Remove leading and trailing whitespaces ###
	repo_location=`echo $REPOSITORY_LOCATION |sed -e 's/^ *//g' -e 's/ *$//g'`
	destination=`echo $REPOSITORY_HOST|sed -e 's/^ *//g' -e 's/ *$//g'`
	uname=`echo $USERNAME |sed -e 's/^ *//g' -e 's/ *$//g'`
	pwd=`echo $PASSWORD |sed -e 's/^ *//g' -e 's/ *$//g'`

	if [ "$repo_location" != "" ] ; then
                if [ "$destination" != "" ] ; then
                        createrepo ./RPMS/noarch/
                        createrepo ./RPMS/x86_64/
                        createrepo ./SRPMS/
                        if [ $uname == "" ] ; then
                              echo "No username provided in the configuration file."
                              echo "Enter the username:"
                              read $uname
                        fi
                        if [ $pwd == "" ] ; then
                              echo "No password provided in the configuration file."
                              echo "Enter the password:"
                              read -s $pwd
                        fi
                        url="$uname@$destination:$repo_location"
                        echo $url
                        ./scp_the_repo.exp "RPMS/" $url $PASSWORD
                        ./scp_the_repo.exp "SRPMS/" $url $PASSWORD
                        if [ $? -ne 0 ]; then
                             echo "Cannot copy the repositories to $destination\n"
                             exit -1
                        fi
                        echo "Copied the repo to the location on the destination"
                        exit 0
                fi
                if [ ! -e $repo_location ] ; then
                       mkdir -p $repo_location
                fi
                cp -r RPMS SRPMS $repo_location
                createrepo $REPOSITORY_LOCATION/RPMS/noarch/
                createrepo $REPOSITORY_LOCATION/RPMS/x86_64/
                createrepo $REPOSITORY_LOCATION/SRPMS/
                echo "Build repository created at $repo_location."
                exit 0
	fi
	echo "Cannot create repository. $repo_location has empty value in repository.cfg"
}

##
## Check for command line argument validity
##

GETOPT=`getopt -o 'v' -l work-dir:,without-test,without-server,without-javadoc,without-debug,createrepo:,verbose -n "$0" -- "$@"`

if [ $? != 0 ] ; then
    Usage
    exit 255
fi

OPTIONS=()
eval set -- "$GETOPT"

VERBOSE=

while true ; do
    case "$1" in
        --work-dir) WORK_DIR="$2" ; shift 2 ;;
        --without-test) OPTIONS+=(--without test) ; shift ;;
        --without-server) OPTIONS+=(--without server) ; shift ;;
        --without-javadoc) OPTIONS+=(--without javadoc) ; shift ;;
        --without-debug) OPTIONS+=(--define "debug_package %{nil}") ; shift ;;
        --createrepo) CREATEREPO="Y" ; REPO_CFG_FILE="$2" ; shift 2 ;;
        -v) ;&
        --verbose)
            OPTIONS+=(--define "_verbose 1") ;
            VERBOSE=1 ;
            shift ;;
        --) shift ; break ;;
        *) echo "$0: unrecognized option '$1'" 1>&2 ; exit 255 ;;
    esac
done

if [ $# -ne 1 ] ; then
	Usage
	exit 255
fi

if	[ $1 = "srpm" ] ; then
	RPMBUILD_OP="-bs"
elif [ $1 = "rpms" ] ; then
	RPMBUILD_OP="-ba"
else
	Usage
	exit 255
fi

