#!/bin/bash
set -euo pipefail
repo_root="$(git rev-parse --show-toplevel)"
cd "$repo_root"
if [ ! -f SOURCE ]; then
echo "ERROR: SOURCE not found in $repo_root" >&2
exit 1
fi
tag="$(head -1 SOURCE)"
if [ -z "$tag" ]; then
echo "ERROR: SOURCE is empty (expected a git tag on the first line)" >&2
exit 1
fi
KERNEL_REPO="${KERNEL_REPO:-}"
if [ -z "$KERNEL_REPO" ] && [ -f ebs-build.conf ]; then
KERNEL_REPO="$(sed -nE 's/^[[:space:]]*KERNEL_REPO[[:space:]]*=[[:space:]]*(.*)[[:space:]]*$/\1/p' ebs-build.conf | head -1)"
fi
if [ -z "$KERNEL_REPO" ]; then
echo "ERROR: KERNEL_REPO not set." >&2
echo "Add a line to your local ebs-build.conf (gitignored):" >&2
echo " KERNEL_REPO=~/git/openeuler/kernel # or a git URL" >&2
echo "or override per-invocation:" >&2
echo " KERNEL_REPO=/path/to/kernel bash scripts/gen-source-tarball.sh" >&2
exit 1
fi
work="$KERNEL_REPO"
tmp_clone=""
if git -C "$KERNEL_REPO" rev-parse --git-dir >/dev/null 2>&1; then
if ! git -C "$KERNEL_REPO" rev-parse -q --verify "refs/tags/$tag" >/dev/null 2>&1; then
echo "Fetching tag $tag from origin ..."
git -C "$KERNEL_REPO" fetch origin "refs/tags/$tag:refs/tags/$tag"
fi
else
tmp_clone="$(mktemp -d)"
echo "Cloning $KERNEL_REPO at $tag (shallow) ..."
if ! git clone --depth 1 --branch "$tag" "$KERNEL_REPO" "$tmp_clone" >/dev/null 2>&1; then
echo "ERROR: failed to fetch $KERNEL_REPO at tag $tag" >&2
rm -rf "$tmp_clone"
exit 1
fi
work="$tmp_clone"
fi
echo "Archiving $tag -> kernel.tar.gz ..."
git -C "$work" archive --format=tar.gz --prefix=kernel/ "$tag" -o "$repo_root/kernel.tar.gz"
[ -n "$tmp_clone" ] && rm -rf "$tmp_clone"
echo "Done: $(ls -lh kernel.tar.gz | awk '{print $5}')"