#!/bin/bash

# Generate build information for Hugo
# This script collects git information and build metadata

set -euo pipefail

# Create data directory if it doesn't exist
mkdir -p data

# Get git information
GIT_COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown")
GIT_COMMIT_SHORT=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")
GIT_BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "unknown")
GIT_TAG=$(git describe --tags --exact-match 2>/dev/null || echo "")
GIT_DIRTY=""

# Check if working directory is dirty
if git diff-index --quiet HEAD -- 2>/dev/null; then
    GIT_DIRTY="false"
else
    GIT_DIRTY="true"
fi

# Get build information
BUILD_TIME=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
BUILD_TIME_HUMAN=$(date -u +"%Y-%m-%d %H:%M UTC")
BUILD_USER=$(whoami 2>/dev/null || echo "unknown")
BUILD_HOST=$(hostname 2>/dev/null || echo "unknown")

# Create JSON file for Hugo
cat > data/build_info.json << EOF
{
  "git_commit": "${GIT_COMMIT}",
  "git_commit_short": "${GIT_COMMIT_SHORT}",
  "git_branch": "${GIT_BRANCH}",
  "git_tag": "${GIT_TAG}",
  "git_dirty": ${GIT_DIRTY},
  "build_time": "${BUILD_TIME}",
  "build_time_human": "${BUILD_TIME_HUMAN}",
  "build_user": "${BUILD_USER}",
  "build_host": "${BUILD_HOST}"
}
EOF

echo "✓ Build info generated: data/build_info.json"
echo "  Git: ${GIT_BRANCH}@${GIT_COMMIT_SHORT}${GIT_TAG:+ (${GIT_TAG})}"
echo "  Built: ${BUILD_TIME_HUMAN} by ${BUILD_USER}"