#!/usr/bin/env sh

set -o pipefail
set -o nounset

source ${CI_PROJECT_DIR}/ci/stack_env.sh

if [ ! -d /squashfs-cache ]
then
    mkdir -p /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"
        empty=(mktemp -d)
        sqfs_base_image=/squashfs-cache/${stack}-${environment}-${squash_base}-initial.sqfs
        mksquashfs ${empty} ${sqfs_base_image}
    else
        echo "Found ${sqfs_base_image}"
    fi

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

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

    echo "Linking ${sqfs_image} -> ${sqfs_base_image}"
else
    if [ ${sqfs_image} != /squashfs-cache/${stack}-${environment}-${squash_id}.sqfs ];
    then
        cd /squashfs-cache
        ln -sf $(basname ${sqfs_image}) ${stack}-${environment}-${squash_id}.sqfs
        cd
    fi
    echo "Found ${sqfs_image}"
fi


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

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