#!/usr/bin/env bash

set -o errexit
set -o nounset
set -o pipefail
#set -o xtrace

export TMP=/scratch/rico/tmp

#source "/scratch/rico/new/env.bash"

export PLANEMO_GLOBAL_WORKSPACE=/scratch/rico/planemo
export PLANEMO_GLOBAL_CONFIG_PATH=${PLANEMO_GLOBAL_WORKSPACE}/.planemo.yml
CLEAN=0
CLEAN=1

if [ -e "/scratch/rico/galaxy" ]; then
    z_time=$(stat --format="%Z" "/scratch/rico/galaxy")

    w_time=$(stat --format="%W" "/scratch/rico/galaxy")
    if [ $w_time -ne 0 ]; then
        if [ $w_time -lt $z_time ]; then
            z_time="$w_time"
        fi
    fi

    now=$(date +%s)
    delta=$(( now - z_time ))
    if [ $delta -ge 86400 ]; then
        CLEAN=1
    fi
else
    CLEAN=1
fi

if [ $CLEAN -ne 0 ]; then
    rm -rf /scratch/rico/galaxy
    rm -rf "$PLANEMO_GLOBAL_WORKSPACE"
    rm -rf /scratch/rico/.npm 
    mkdir /scratch/rico/.npm
fi

rm -rf /tmp/tmp* "$TMP/tmp*"

export GALAXY_SLOTS=64
export GALAXY_MEMORY_MB=262144

if [ $CLEAN -ne 0 ]; then
    planemo test \
        --galaxy_root /scratch/rico/galaxy \
        --docker \
        --no_cleanup \
        2>&1 \
        | tee test.out
else
    planemo test \
        --galaxy_root /scratch/rico/galaxy \
        --docker \
        --no_docker_sudo \
        --no_cleanup \
        2>&1 \
        | tee test.out
fi

# Galaxy upload tool fails when using planemo server on galaxy release branch 24
# 
# rm -rf /scratch/rico/galaxy; planemo serve --galaxy_branch release_23.2 --galaxy_root /scratch/rico/galaxy
# rm -rf /scratch/rico/galaxy; planemo serve --galaxy_branch release_24.0 --galaxy_root /scratch/rico/galaxy


