#!/bin/bash -xe

# Cleaning pre compilation
/usr/bin/rm -rf ${TOP_DIR}/BUILD/* ${TOP_DIR}/RPMS/* ${TOP_DIR}/SRPMS/* ${TOP_DIR}/SOURCES/* ${TOP_DIR}/BUILDROOT/*

# retrieving sources
/usr/bin/git clone -b ${SDRMAA_VERSION} ${SDRMAA_URL} ${TOP_DIR}/SOURCES/slurm-drmaa-${SDRMAA_VERSION}

/usr/bin/sed -i "s|^Version:.*|Version: ${SDRMAA_VERSION_SPEC}|g" ${TOP_DIR}/SOURCES/slurm-drmaa-${SDRMAA_VERSION}/slurm-drmaa.spec
/usr/bin/sed -i "s|^Release:.*|Release: ${SDRMAA_RELEASE_SPEC}|g" ${TOP_DIR}/SOURCES/slurm-drmaa-${SDRMAA_VERSION}/slurm-drmaa.spec

/usr/bin/cp ${TOP_DIR}/SOURCES/slurm-drmaa-${SDRMAA_VERSION}/slurm-drmaa.spec ${TOP_DIR}/SPECS/slurm-drmaa.spec
tar --exclude-vcs --totals --create --verbose --gz --file  ${TOP_DIR}/SOURCES/slurm-drmaa-${SDRMAA_VERSION}.tar.gz -C ${TOP_DIR}/SOURCES/ slurm-drmaa-${SDRMAA_VERSION}

# installing dependencies
/bin/yum makecache fast
/usr/bin/touch /var/lib/rpm/*

/usr/bin/cp ${TOP_DIR}/rpmmacros ~/.rpmmacros
/usr/bin/echo "${SDRMAA_BUILD_DEP_OPTIONS}" | /usr/bin/xargs /bin/yum-builddep -y ${TOP_DIR}/SPECS/slurm-drmaa.spec

# compiling rpm
/usr/bin/rpmbuild --clean --target=${SDRMAA_DEST_ARCH} ${SDRMAA_BUILD_OPTIONS} -ba ${TOP_DIR}/SPECS/slurm-drmaa.spec

# moving rpms to artifacts directories
/usr/bin/find ${TOP_DIR}/RPMS/ -type f -iname "*.rpm" -exec /usr/bin/cp -v {} ${TOP_DIR}/ARTIFACTS/ \;

# installing result to be used when compiling SDRMAA
/usr/bin/yum install -y ${TOP_DIR}/ARTIFACTS/*

# Cleaning post compilation
/usr/bin/rm -rf ${TOP_DIR}/BUILD/* ${TOP_DIR}/RPMS/* ${TOP_DIR}/SRPMS/* ${TOP_DIR}/SOURCES/* ${TOP_DIR}/BUILDROOT/*