#!/bin/bash

if [ -z "$1" ]; then
    echo "ERROR: No version file name provided. Usage: $0 <version_file>"
    exit 1
fi

VERSION_FILE="$1"

if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
    VERSION=$(git describe 2>/dev/null || git rev-parse --short HEAD || echo "v0.0.0-unknown")
    DIRTY=$(git diff-index --quiet HEAD -- || echo "-dirty")
    FULL_VERSION="${VERSION}${DIRTY}"
    echo "$FULL_VERSION" >"$VERSION_FILE"
else
    if [ -f "$VERSION_FILE" ]; then
        echo "INFO: $VERSION_FILE already exists. Please update it manually if needed."
    else
        echo "ERROR: Not in a Git repository, and $VERSION_FILE does not exist. Unable to generate version!"
        exit 1
    fi
fi