#!/bin/sh

# local/release/post-release
# Script to post the most recent release make on the current machine
# into the standard location on the wes-hazy server.

PROGRAM_NAME=`basename $0`

RELEASE_TYPE="" ; VERSION=""

# Process command line options:

while [ ! "$1" = "" ] ; do
    OPT="$1" ; shift
    
    case ${OPT} in
	
	-help | -? | --help )
	echo "${PROGRAM_NAME} Options:"
	echo "           -iris : Make IRIS file set"
	echo "            -rda : Make RDA file set, else IRIS"
	echo "           -help : Print this text"
	echo "  -version <ver> : Specify release version"
	exit 0
	;;
	
	-iris )
	if [ "${RELEASE_TYPE}" = "rda" ] ; then 
	    echo "Cannot supply both -rda and -iris options" 1>&2 ; exit 1
	fi
	RELEASE_TYPE="iris"
	;;
	
	-rda )
	if [ "${RELEASE_TYPE}" = "iris" ] ; then 
	    echo "Cannot supply both -rda and -iris options" 1>&2 ; exit 1
	fi
	RELEASE_TYPE="rda"
	;;
	
	-version )
	if [ "${1}" = "" ] ; then
	    echo "Missing version string for -version" 1>&2 ; exit 1
	else
	    VERSION="${1}" ; shift
	fi ;;
    esac
    
done

if [ "${RELEASE_TYPE}" = "" ] ; then
    echo "Sorry, must specify a release type"
    exit 1
fi

# Figure out OS name
KERNEL=`uname -r`
KERNEL_PRE_DASH="${KERNEL%%-*}" ;

case ${KERNEL_PRE_DASH} in
    2.6.32 )
	OS_NAME=CENTOS6
	;;
    3.10.0 )
	OS_NAME=CENTOS7
	;;
    4.18.0 )
	OS_NAME=CENTOS8
	;;
    * )
	echo "Sorry, unrecognized kernel version '${KERNEL}'"
	exit 1
	;;
esac

if [ "${VERSION}" = "" ] ; then
    VERSION="`show_machine_code --version | sed 's/ *$//' | sed 's/.* //'`"
fi

# The location of the source files
#
SOURCE_ROOT="/usr/sigmet/builds"
SOURCE_DIR=${SOURCE_ROOT}/${RELEASE_TYPE}-${VERSION}

# The location of the target directory
TARGET_ROOT="/images/builds"
TARGET_DIR=${TARGET_ROOT}/${VERSION}/${OS_NAME}/${RELEASE_TYPE}

if [ ! -r ${SOURCE_DIR} ] ; then
    echo "Sorry, ${SOURCE_DIR} does not exist"
    exit 1
fi

if [ -r ${TARGET_DIR} ] ; then
    echo "ERROR: ${TARGET_DIR} exists, please remove and run again"
    EXIT_VAL=1
else
    EXIT_VAL=0

    mkdir -p ${TARGET_DIR}
    cp -pv ${SOURCE_DIR}/* ${TARGET_DIR}/
fi

exit ${EXIT_VAL}
