#!/bin/bash

# Function to check if input is a valid year
is_valid_year() {
    if [[ $1 =~ ^[0-9]{4}$ ]]; then
        return 0
    else
        return 1
    fi
}

# Function to format date for git
format_date() {
    date -u -d "$1" "+%Y-%m-%d %H:%M:%S" 2>/dev/null || date -u -j -f "%Y-%m-%d" "$1" "+%Y-%m-%d %H:%M:%S" 2>/dev/null
}

# Prompt for the year
read -p "Enter the year to fill with commits (YYYY): " year

# Validate the input
if ! is_valid_year "$year"; then
    echo "Error: Invalid year format. Please enter a 4-digit year (e.g., 2023)."
    exit 1
fi

# Create a new directory and initialize a git repository
mkdir -p year_of_commits
cd year_of_commits

# Initialize git repository if it doesn't exist
if [ ! -d .git ]; then
    git init
fi

# Set the start and end dates for the specified year
start_date="${year}-01-01"
end_date="${year}-12-31"

# Convert dates to seconds since epoch
start_seconds=$(date -d "$start_date" +%s 2>/dev/null || date -j -f "%Y-%m-%d" "$start_date" +%s 2>/dev/null)
end_seconds=$(date -d "$end_date" +%s 2>/dev/null || date -j -f "%Y-%m-%d" "$end_date" +%s 2>/dev/null)

if [ -z "$start_seconds" ] || [ -z "$end_seconds" ]; then
    echo "Error: Unable to process dates. Please run this script on a system with GNU date or BSD date."
    exit 1
fi

# Loop through each day of the year
for (( d=$start_seconds; d<=$end_seconds; d+=86400 )); do
    # Generate a random number of commits for this day (0-5)
    num_commits=$((RANDOM % 6))
    
    for (( i=0; i<$num_commits; i++ )); do
        # Create a dummy file
        current_date=$(date -u -d "@$d" "+%Y-%m-%d" 2>/dev/null || date -u -r "$d" "+%Y-%m-%d" 2>/dev/null)
        file_name="file_${current_date}_${i}.txt"
        echo "Commit on $current_date" > "$file_name"
        
        # Stage, commit, and set the commit date
        git add "$file_name"
        commit_date=$(format_date "$current_date")
        GIT_AUTHOR_DATE="$commit_date" GIT_COMMITTER_DATE="$commit_date" git commit -m "Commit $((i+1)) for $current_date"
    done
done

echo "Finished generating commits for $year in the year_of_commits directory!"
echo "To push these commits to GitHub:"
echo "1. Create a new repository on GitHub"
echo "2. Run the following commands:"
echo "   git remote add origin <your-github-repo-url>"
echo "   git push -u origin master"