#!/bin/bash

# Script to update GitInfo.swift and Info.plist with current git information
# This should be run as a build phase in Xcode

# Get current git information
COMMIT_HASH=$(git rev-parse HEAD)
COMMIT_DATE=$(git log -1 --format="%ci")
SHORT_COMMIT_HASH=$(git rev-parse --short HEAD)
COMMIT_DATE_FORMATTED=$(git log -1 --format="%b %d, %Y")

# Define file paths
GITINFO_FILE="${SRCROOT}/CCTray/Utilities/GitInfo.swift"
INFOPLIST_FILE="${SRCROOT}/CCTray/Info.plist"

# Create the updated GitInfo.swift content
cat > "${GITINFO_FILE}" << EOF
//
//  GitInfo.swift
//  CCTray
//
//  Created by Robert Goniszewski on 14/07/2025.
//  Auto-generated by build script - do not edit manually
//

import Foundation

struct GitInfo {
    static let repositoryURL = "https://github.com/goniszewski/cctray"
    static let authorHandle = "@goniszewski"
    static let authorName = "Robert Goniszewski"
    
    // Auto-updated by build script
    static let commitHash = "${COMMIT_HASH}"
    static let commitDate = "${COMMIT_DATE}"
    static let shortCommitHash = "${SHORT_COMMIT_HASH}"
    
    static var formattedCommitDate: String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
        
        if let date = formatter.date(from: commitDate) {
            formatter.dateStyle = .medium
            formatter.timeStyle = .short
            return formatter.string(from: date)
        }
        
        return commitDate
    }
    
    static var repositoryDisplayURL: String {
        return repositoryURL.replacingOccurrences(of: "https://", with: "")
    }
}
EOF

# Update project build settings with current commit information
PROJECT_FILE="${SRCROOT}/CCTray.xcodeproj/project.pbxproj"
if [ -f "${PROJECT_FILE}" ]; then
    # Update the INFOPLIST_KEY_CFBundleGetInfoString with current commit info
    sed -i '' "s/INFOPLIST_KEY_CFBundleGetInfoString = \".*\";/INFOPLIST_KEY_CFBundleGetInfoString = \"CCTray - macOS menu bar app for Claude Code usage monitoring with real-time cost tracking, burn rate monitoring, and session analytics. Latest commit: ${SHORT_COMMIT_HASH} (${COMMIT_DATE_FORMATTED})\";/g" "${PROJECT_FILE}"
    
    echo "Updated project build settings with commit info"
fi

echo "Updated GitInfo.swift and Info.plist with commit ${SHORT_COMMIT_HASH}"