#!/usr/bin/env sh

set -o pipefail


source ${CI_PROJECT_DIR}/ci/stack_env.sh

if [ "x${CI_DEFAULT_BRANCH}" != "x" ]
then
   squash_base=${CI_DEFAULT_BRANCH}
else
   squash_base=master
fi

if [ "x${CI_MERGE_REQUEST_IID}" != "x" ]
then
    squash_id=${CI_MERGE_REQUEST_IID}
elif [ "x${CI_COMMIT_BRANCH}" != "x" ]
then
    squash_id=${CI_MERGE_REQUEST_IID}
else
    squash_id="local"
fi

set -o nounset

if [ -d /squashfs-cache ]
then
    mkdir /squashfs-cache
fi

# Check if MR as squashfs
sqfs_image=$(ls -t1 /squashfs-cache/${stack}-${environment}-${squash_id}.sqfs 2> /dev/null | head -1)
if [ $? -ne 0 ]
then
    echo "No MR ($squash_id) squashfs found"
    # Check if MR default branch as squashfs
    sqfs_base_image=$(ls -t1 /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"
        mkdir /tmp/empty
        mksquashfs /tmp/empty /squashfs-cache/${stack}-${environment}-${squash_base}.sqfs
    else
        echo "Found ${sqfs_base_image}"
    fi

    # Link MR sqaushfs to the one of default branch
    ln -sf /squashfs-cache/${stack}-${environment}-${squash_base}.sqfs \
        /squashfs-cache/${stack}-${environment}-${squash_id}.sqfs

    echo "Linking ${stack}-${environment}-${squash_id}.sqfs -> ${stack}-${environment}-${squash_base}.sqfs"
else
    echo "Found ${sqfs_image}"
fi


if [ -d /overlayfs ]
then
    mkdir -p /overlayfs
fi

if [ -d /overlayfs/upper ]
then
    mkdir -p /overlayfs/upper
    mkdir -p /overlayfs/wd
fi
