#!/bin/sh
# Copyright (c) 2012-2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.

export LC_ALL=C
if [ $# -gt 1 ]; then
    cd "$2" || exit 1
fi
if [ $# -gt 0 ]; then
    FILE="$1"
    shift
    if [ -f "$FILE" ]; then
        INFO="$(head -n 1 "$FILE")"
    fi
else
    echo "Usage: $0 <filename> <srcroot>"
    exit 1
fi

GIT_DESCRIPTION=""
if [ "${BITCOIN_GENBUILD_NO_GIT}" != "1" ] && [ -e "$(command -v git)" ] && [ "$(git rev-parse --is-inside-work-tree 2>/dev/null)" = "true" ]; then
    # clean 'dirty' status of touched files that haven't been modified
    git diff >/dev/null 2>/dev/null

    # override using the tag name from git, i.e. string like "v20.0.0-beta.8-5-g99786590df6f-dirty"
    GIT_DESCRIPTION=$(git describe --abbrev=12 --dirty 2>/dev/null)
fi

if [ -n "$GIT_DESCRIPTION" ]; then
    NEWINFO="#define BUILD_GIT_DESCRIPTION \"$GIT_DESCRIPTION\""
else
    NEWINFO="// No build information available"
fi

# only update build.h if necessary
if [ "$INFO" != "$NEWINFO" ]; then
    echo "$NEWINFO" >"$FILE"
fi
