# This script should only be called from the "archive_sparc.sh" script
# The processing in this script will run *every* time data is collected for archiving.
# Anything less frequent than that should be moved to its own cron job.
# This script should only be run if the "sparchive_post" command is available in the PATH.

oops() {
    echo "ERROR: $*"
    if [ -d $work_dir ]; then
        echo "INFO: Removing temporary work directory: $work_dir"
        rm -rf $work_dir
    fi
    exit 1
}

if [ "`which sparchive_post`" == "" ]; then
    echo "ERROR: 'sparchive_post' command is required to run this post processing script"
    exit 1
fi

EXP_NAME=$1
date_yyyymmdd=$2
# XXX: This script should only deal with data from the cache/raw (no incoming data)
EXP_PATH="${SPARCHIVE_CACHE_ROOT}/${EXP_NAME}"
work_dir="NOT_SET"

# Daily jobs
echo "Running windpro profile post processing for ${EXP_NAME} on $date_yyyymmdd"

work_dir=`mktemp -d ${SPARCHIVE_TMP_ROOT}/post_${date_yyyymmdd}_XXXXXX` || oops "Failed to create temporary work directory"
chmod 777 $work_dir || oops "Failed to change temporary work directory permissions"
cd $work_dir || oops "Couldn't change to temporary directory"
echo "Created temporary working directory: $work_dir"

########################
# Run WindPro DMV2NCDF #
########################

echo "Creating WindPro profile files from data on ${date_yyyymmdd}"
sudo -u timw ${SPARCHIVE_SCRIPTS_ROOT}/run_windpro_process_profile.sh ${EXP_PATH}/${WINDPRO}/${date_yyyymmdd}/raw ${work_dir} || oops "Could not make windpro profile files"

echo "Moving WindPro profile files to Cache location"
sparchive_post -vvv --experiment ${EXP_NAME} ${WINDPRO} "profiles" ${date_yyyymmdd} *.dat *.png || oops "Could not archive windpro profile files"

echo "Removing temporary work directory: $work_dir"
rm -rf ${work_dir} || oops "Failed to remove the work directory: $work_dir"

