#!/bin/bash


if [ "$OS" == "win7" ]; then
    # there is no docker on windows
    CONTAINER_ID=0
else
    CONTAINER_ID=$(cat /proc/self/cgroup | head -n 1 | cut -d '/' -f3)
fi

# default stage is coverage
if [[ "$CAMITK_CI_STAGE" == "" ]]; then 
    CAMITK_CI_STAGE="$STAGE_COVERAGE";
fi

# default mode is Continuous for develop, Experimental for any other branches
if [[ "$CAMITK_CI_MODE" == "" ]]; then 
    if [[ "$CI_COMMIT_REF_NAME" == "develop" ]]; then 
        CAMITK_CI_MODE="Continuous"; 
    else 
        CAMITK_CI_MODE="Experimental"; 
    fi
fi

# Check git commit message
MESSAGE_CHECK=$(git log -n 1 | grep --quiet --extended-regexp '/check' && echo "true" || echo "false")
MESSAGE_CONFIGURE=$(git log -n 1 | grep --quiet --extended-regexp '/configure' && echo "true" || echo "false")
MESSAGE_BUILD=$(git log -n 1 | grep --quiet --extended-regexp '/build' && echo "true" || echo "false")
MESSAGE_TEST=$(git log -n 1 | grep --quiet --extended-regexp '/test' && echo "true" || echo "false")
MESSAGE_COVERAGE=$(git log -n 1 | grep --quiet --extended-regexp '/coverage' && echo "true" || echo "false")

# store variables in a local file
TRIGGER_FILE=/tmp/trigger-stage.txt
rm -f $TRIGGER_FILE
echo "Triggered stages:" > $TRIGGER_FILE

# check MESSAGE variables and CAMITK_CI_STAGE value
if [[ "$MESSAGE_CHECK" == "true" || "$CAMITK_CI_STAGE" -ge $STAGE_CHECK ]]; then 
    echo "TRIGGER_STAGE_CHECK" >> $TRIGGER_FILE
fi

if [[ "$MESSAGE_CONFIGURE" == "true" || "$CAMITK_CI_STAGE" -ge $STAGE_CONFIGURE ]]; then 
    echo "TRIGGER_STAGE_CONFIGURE" >> $TRIGGER_FILE
fi

if [[ "$MESSAGE_BUILD" == "true" || "$CAMITK_CI_STAGE" -ge $STAGE_BUILD ]]; then
    echo "TRIGGER_STAGE_BUILD" >> $TRIGGER_FILE
fi

if [[ "$MESSAGE_TEST" == "true" || "$CAMITK_CI_STAGE" -ge $STAGE_TEST ]]; then
    echo "TRIGGER_STAGE_TEST" >> $TRIGGER_FILE
fi

if [[ "$MESSAGE_COVERAGE" == "true" || "$CAMITK_CI_STAGE" -ge $STAGE_COVERAGE ]]; then
    echo "TRIGGER_STAGE_COVERAGE" >> $TRIGGER_FILE
fi


# output all information to report file
echo "Docker container id....... $CONTAINER_ID" > /tmp/report.txt
echo "Job....................... $CI_JOB_NAME" >> /tmp/report.txt
echo "Build Directory........... $PROJECT_BUILD_DIR" >> /tmp/report.txt
echo "Log Directory............. $PROJECT_LOG_DIR" >> /tmp/report.txt
echo "Branch.................... $CI_COMMIT_REF_NAME" >> /tmp/report.txt
echo "CAMITK_CI_MODE............ $CAMITK_CI_MODE" >> /tmp/report.txt
echo "CAMITK_CI_STAGE........... $CAMITK_CI_STAGE" >> /tmp/report.txt

# cleanup log directory
if [ -d ${PROJECT_LOG_DIR} ] ; then 
    rm -rf ${PROJECT_LOG_DIR};
fi
mkdir -p ${PROJECT_LOG_DIR}

# show report
cat /tmp/report.txt
cp -f $TRIGGER_FILE ${PROJECT_LOG_DIR}
cat ${PROJECT_LOG_DIR}/trigger-stage.txt
