#!/bin/bash

PROG="`/bin/basename ${0}`"
SRPM_ORIG="${1}"
SRPM_TARGETDIR="${2}"

SRPM_FILE="${SRPM_ORIG}"
SRPM_FILENAME="`/bin/echo ${SRPM_FILE} | /bin/sed -e 's/^.*\///'`"
SRPM_TMPDIR="/tmp/${PROG}.$$"
/bin/mkdir -p ${SRPM_TMPDIR}/content > /dev/null 2>&1

function exit_now() {
	exit_code="${1}"
	cd /tmp
	if [ -n "${SRPM_TMPDIR}" ]; then
		if [ -d "${SRPM_TMPDIR}" ]; then
			/bin/rm -rf ${SRPM_TMPDIR}
		fi
	fi
	exit ${exit_code}
}

# Fail if no options given.
if [ -z "${SRPM_ORIG}" ]; then
	/bin/echo -e "\nUsage:\n   ${PROG} some_package.src.rpm [target_directory]"
	exit_now 1
fi

# Validate target_directory
if [ -n "${SRPM_TARGETDIR}" ]; then
	if [ ! -d "${SRPM_TARGETDIR}" ]; then
		/bin/echo -e "\nERROR:\n   target_directory (${SRPM_TARGETDIR}) does not exist!"
		exit_now 2
	fi
else
	if [ -d "${HOME}/el5" ]; then
		SRPM_TARGETDIR="${HOME}/el5"
	else
		SRPM_TARGETDIR="${HOME}"
	fi
fi

# Make sure target_directory is writable.
if [ ! -w "${SRPM_TARGETDIR}" ]; then
	/bin/echo -e "\nERROR:\n   target_directory (${SRPM_TARGETDIR}) is not writable!"
	exit_now 3
fi


# Validate the filename is a SRPM.
SRPM_ISSRPM="0`/bin/echo ${SRPM_FILENAME} | /bin/sed -e 's/^.*\.src\.rpm$/1/'`"
if [ ${SRPM_ISSRPM} -ne 1 ]; then
	/bin/echo -e "\nERROR:\n   ${SRPM_FILENAME} does not end in .src.rpm!"
	exit_now 4
fi

# Check if file begins with http or ftp and download.
SRPM_ISREMOTE="0`/bin/echo ${SRPM_ORIG} | /bin/sed -e 's/^\(f\|ht\)tp:.*$/1/'`"
if [ ${SRPM_ISREMOTE} -eq 1 ]; then
	SRPM_FILE="${SRPM_TMPDIR}/${SRPM_FILENAME}"
	/bin/echo -n "   Downloading ${SRPM_FILENAME}..."
	/usr/bin/wget ${SRPM_ORIG} -O ${SRPM_FILE} > /dev/null 2>&1
	RETVAL=$?
	if [ $RETVAL -ne 0 ]; then
		/bin/echo "FAILED."
		exit_now 5
	else
		/bin/echo "done."
	fi
fi

# Check if SRPM is valid and get name.
SRPM_NAME="`rpm -qp --qf '%{NAME}' ${SRPM_FILE} 2>/dev/null`"
if [ -z "${SRPM_NAME}" ]; then
	/bin/echo -e "\nERROR:\n   Cannot get NAME from ${SRPM_FILE}!"
	exit_now 5
fi

# Check SRPM dest path already exists
if [ -d "${SRPM_TARGETDIR}/${SRPM_NAME}" ]; then
	/bin/echo -e "\nERROR:\n   ${SRPM_TARGETDIR}/${SRPM_NAME} already exists!"
	exit_now 6
fi


# Unpack SRPM
/bin/echo -n "   Unpacking ${SRPM_FILENAME}..."
cd ${SRPM_TMPDIR}/content
/usr/bin/rpm2cpio ${SRPM_FILE} | /bin/cpio -i > /dev/null 2>&1
RETVAL=$?
if [ $RETVAL -ne 0 ]; then
	/bin/echo "FAILED."
	exit_now 7
else
	/bin/echo "done."
fi

# Move SRPM contents
/bin/echo -n "   Copying to ${SRPM_NAME}..."
cd ${SRPM_TMPDIR}
/bin/mv ${SRPM_TMPDIR}/content ${SRPM_TARGETDIR}/${SRPM_NAME}
RETVAL=$?
if [ $RETVAL -ne 0 ]; then
	/bin/echo "FAILED."
	exit_now 8
else
	/bin/echo "done."
fi



# Exit
exit_now 0
