#!/bin/sh

# SPDX-FileCopyrightText: 2023 - 2026 UnionTech Software Technology Co., Ltd.
# SPDX-License-Identifier: LGPL-3.0-or-later

set -e

action=$1
url=$2
ref=$3
workdir=$4

if [ "$action" != "checkout" ]; then
    echo "unsupported git source action: $action" >&2
    exit 1
fi

if ! command -v git > /dev/null 2>&1; then
    echo "git not found, please install git first" >&2
    exit 1
fi

mkdir "$workdir"
git -C "$workdir" init
git -C "$workdir" remote add origin "$url"

git -C "$workdir" fetch --depth 1 -n origin -- "$ref"
git -C "$workdir" reset --hard FETCH_HEAD

if [ -n "${GIT_SUBMODULES:-}" ]; then
    git -C "$workdir" submodule update --init --recursive --depth 1
    git -C "$workdir" submodule foreach git reset --hard HEAD
fi

git -C "$workdir" rev-parse --verify HEAD
