#!/usr/bin/env bash
# Description: Archive AERIoe data from the SPARC AERI instrument for a specific day

ENV=/opt/metobs/sparchive
LOGDIR=$ENV/log
SCRIPT_NAME=$(basename $0)
SCRIPT_NAME=${SCRIPT_NAME/.sh/}

DATE=$1
if [ -z "$DATE" ]; then
   DATE=`date +%Y%m%d`
fi
LOCK="${ENV}/lock/${SCRIPT_NAME}.lock"
logfile="${LOGDIR}/${SCRIPT_NAME}.log"

# Get environment variables and common functions
source $ENV/scripts/sparchive_env.sh
AERIOE_INCOMING_DIR="${SPARCHIVE_INCOMING_ROOT}/current/aerioe"

(
    flock -x -n 200 || log_info "Script is already running, will not run again."

    if [ ! -d $AERIOE_INCOMING_DIR ]; then
        log_info "Creating incoming directory $AERIOE_INCOMING_DIR..."
        mkdir -p $AERIOE_INCOMING_DIR
    fi

    log_info "$(date +%Y-%m-%dT%H:%M:%S): Running archive jobs for ${DATE}" >> $logfile
    #log_info "$(date +%Y-%m-%dT%H:%M:%S): Running archive jobs for the past 3 days" >> $logfile
    $ENV/bin/python -m metobscommon.archive.incoming -vv --product-version 0 -l $logfile c1 sparc.aeri $AERIOE_INCOMING_DIR/*$DATE*.{png,cdf} --dates ${DATE} --experiment current
    # Hacky to get already made latest files put in the archive
    cp $AERIOE_INCOMING_DIR/{latest_*,*last_*}.png ${SPARCHIVE_CACHE_ROOT}/current/aeri/level_c1/version_00/

    log_info "Done"

) 200>$LOCK
