#!/usr/bin/env sh

set -o pipefail
set -o nounset
set -o errexit
source ${CI_PROJECT_DIR}/ci/stack_env.sh

mkdir -p ${CI_DATA_ST}/overlayfs
mkdir -p ${CI_DATA_ST}/homes
mkdir -p ${CI_DATA_ST}/deconcretize

for i in squashfs-cache buildcache/$environment spack-mirror
do
    if [ ! -e ${CI_DATA_LT}/$i ]
    then
        mkdir -p ${CI_DATA_LT}/$i
    fi
done


image_name=${stack}-${environment}-${squash_id}-${CI_PIPELINE_ID}

set +o errexit
# Check if MR as squashfs
sqfs_image=$(ls -t1 ${CI_DATA_LT}/squashfs-cache/${image_name}.sqfs 2> /dev/null | head -1)
if [ $? -ne 0 ]
then
    echo "No MR ($squash_id-${CI_PIPELINE_ID}) squashfs found"

    # look for base in the branch
    sqfs_base_image=$(ls -t1 ${CI_DATA_LT}/squashfs-cache/${stack}-${environment}-${squash_id}.sqfs 2> /dev/null | head -1)
    if [ $? -ne 0 ]
    then
        echo "No MR ($squash_id) squashfs found"

        # look for base in default branch
        sqfs_base_image=$(ls -t1 ${CI_DATA_LT}/squashfs-cache/${stack}-${environment}-${squash_base}*.sqfs 2> /dev/null | head -1)
        if [ $? -ne 0 ]
        then
            echo "No default branch ($squash_base) squashfs found"
            echo "Creating an empty one"
            empty=$(mktemp -d)
            sqfs_base_image="${CI_DATA_LT}/squashfs-cache/${stack}-${environment}-${squash_base}-initial.sqfs"
            mksquashfs ${empty} ${sqfs_base_image}
        else
            echo "Found ${sqfs_base_image}"
        fi
    else
        echo "Found ${sqfs_base_image}"
    fi
    set -o errexit

    # Link MR sqaushfs to the one of default branch
    sqfs_image=${CI_DATA_LT}/squashfs-cache/${image_name}.sqfs

    cd ${CI_DATA_LT}/squashfs-cache
    ln -sf $(basename ${sqfs_base_image}) $(basename ${sqfs_image})
    cd -

    echo "Linking ${sqfs_image} -> ${sqfs_base_image}"
else
    set -o errexit
    if [ ${sqfs_image} != ${CI_DATA_LT}/squashfs-cache/${image_name}.sqfs ];
    then
        cd ${CI_DATA_LT}/squashfs-cache
        ln -sf $(basname ${sqfs_image}) ${image_name}.sqfs
        cd
    fi
    echo "Found ${sqfs_image}"
fi
