#!/usr/bin/env bash

# Description: Pull data from the AOSS Rooftop Tower instrument for a specific day
SCRIPT_HOME="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
SCRIPT_NAME=$(basename $0)
SCRIPT_NAME=${SCRIPT_NAME/.sh/}

# Get environment variables and common functions
source $SCRIPT_HOME/metobs_config.sh

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

if [ ! -d $LOGDIR ]; then
    oops "Log directory doesn't exist: $LOGDIR"
    exit 1
fi

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

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

    log_info "$(date +%Y-%m-%dT%H:%M:%S): Running archive jobs for ${DATE}"
    $ENV/bin/python -m metobscommon.archive.incoming -vv -l $logfile --dates=${DATE} 00 aoss.tower "rig_tower.%Y-%m-%d.ascii"

    # Hack to keep the old 'ascii' directory up to date
    # FIXME: Remove this once all new generation scripts work
    year=${DATE:0:4}
    month=${DATE:4:2}
    day=${DATE:6:2}
    link_fn="$TOWER_CACHE_DIR/ascii/${year}/${month}/rig_tower.${year}-${month}-${day}.ascii"
    if [ ! -e $link_fn ]; then
        mkdir -p $TOWER_CACHE_DIR/ascii/${year}/${month}/
        ln -s "$TOWER_PRAW_DIR/${year}/${month}/${day}/rig_tower.${year}-${month}-${day}.ascii" ${link_fn}
    fi

    log_info "Done"

) 200>$LOCK