#! /bin/bash

set -e
set -o pipefail
set -x

# Ensure the log directory exists
mkdir -p logs

# Setup certificates and image version for sysupdate
if [ "${CI_COMMIT_REF_PROTECTED-}" != true ] || [ "${CI_PIPELINE_SOURCE-}" = "schedule" ]; then
    make -C files/boot-keys generate-keys IMPORT_MODE=snakeoil
    export PUSH_SOURCE=1
else
    make -C files/boot-keys generate-keys IMPORT_MODE=import
fi

# Setup the token for pushing to the cache
echo $CACHE_TOKEN >.gitlab-ci/gbm-cache-token

./.gitlab-ci/scripts/generate-buildtream-conf.sh nopush >.gitlab-ci/buildstream-nopush.conf
./.gitlab-ci/scripts/generate-buildtream-conf.sh >.gitlab-ci/buildstream.conf

# Check that the commit timestamps are increasing, as our version numbers depend on that
git log --format=%cd --date=unix | sort --check --reverse --numeric-sort

if [ "${CI_COMMIT_BRANCH-}" = master ]; then
    version_num=$(TZ=UTC git log --format="%cd" --date="format-local:%Y%m%d" | uniq -c | (head -n1 && cat >/dev/null) | awk '{print ($2"."($1-1))}')
    IMAGE_VERSION="nightly.$version_num"
elif [ "${CI_COMMIT_REF_PROTECTED-}" = true ]; then
    IMAGE_VERSION=$(git describe | cut -d - -f 1-2)
else
    target="${CI_MERGE_REQUEST_TARGET_BRANCH_NAME-unknown}"
    if [ "${target}" = master ]; then
        target=nightly
    fi
    IMAGE_VERSION=$(echo "${target}-branch" | sed "s/-/_/g")
fi

# The longest GPT label is of shape "gnomeos_usr_v_%A".
# The longest possible label is 36. So the longest version is 22.
if [ "${#IMAGE_VERSION}" -gt 22 ]; then
    echo "Version is too long" 1>&2
    exit 1
fi

echo "image-version: ${IMAGE_VERSION}" > include/image-version.yml
export IMAGE_VERSION

commit=$(git rev-parse "${CI_MERGE_REQUEST_DIFF_BASE_SHA-HEAD}")
commit_time=$(git log -1 --format=format:%ct "${CI_MERGE_REQUEST_DIFF_BASE_SHA-HEAD}")
commit_date_pretty=$(git show -s --format=%ci "${CI_MERGE_REQUEST_DIFF_BASE_SHA-HEAD}")

echo "filesystem-time: ${commit_time}" >> include/image-version.yml
echo "commit: '${commit}'" >> include/image-version.yml
echo "commit-date-pretty: '${commit_date_pretty}'" >> include/image-version.yml

cat include/image-version.yml

set +x
