#!/bin/bash
# SPDX-License-Identifier: GPL-2.0-only
# Generate kernel.tar.gz (Source0) from the git tag recorded in SOURCE.
#
# The source tarball is NOT stored in this repository — EulerMaker (EBS)
# auto-generates it from the SOURCE tag at build time. Local manual builds
# need this script to produce kernel.tar.gz first.
#
# The kernel source repo is configured (layered, no bashrc editing):
#   1. environment variable:  KERNEL_REPO=/path/to/kernel
#   2. local gitignored file: KERNEL_REPO=~/git/openeuler/kernel  in ebs-build.conf
#   3. error with example (see below)
#
# KERNEL_REPO may be a local git checkout or a git URL. A missing tag in a
# local checkout is fetched from its origin; a URL is shallow-cloned at the tag.
#
# Usage:
#   scripts/gen-source-tarball.sh
#   → creates kernel.tar.gz in repo root (top dir is kernel/)

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

# 配置读取分层:环境变量 > 本地 ebs-build.conf(与 ebs-build.sh conf_get 一致)
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}')"