#!/bin/bash

# Script to create a new branch from main/origin

# Check if branch name is provided
if [ $# -eq 0 ]; then
    echo "Error: Branch name is required"
    echo "Usage: $0 <branch-name>"
    exit 1
fi

# Store branch name from parameter
BRANCH_NAME=$1

# Ensure we have the latest from origin
echo "Fetching latest changes from origin..."
git fetch origin

# Check if we're already on main, if not switch to it
CURRENT_BRANCH=$(git symbolic-ref --short HEAD)
if [ "$CURRENT_BRANCH" != "main" ]; then
    echo "Switching to main branch..."
    git checkout main
fi

# Pull latest changes from main
echo "Pulling latest changes from main..."
git pull origin main

# Create and checkout the new branch
echo "Creating and checking out new branch: $BRANCH_NAME"
git checkout -b "$BRANCH_NAME"

# Stage all changes
echo "Staging all changes..."
git add .

# Ask if user wants to make an initial commit
read -p "Do you want to make an initial commit? (Y/n): " COMMIT_CHOICE

# Default to Yes if Enter is pressed without input
COMMIT_CHOICE=${COMMIT_CHOICE:-Y}

if [[ $COMMIT_CHOICE =~ ^[Yy]$ ]]; then
    # Ask for commit message
    read -p "Enter commit message: " COMMIT_MESSAGE
    
    # Check if commit message is provided
    if [ -n "$COMMIT_MESSAGE" ]; then
        # Make the commit
        echo "Creating commit with message: '$COMMIT_MESSAGE'"
        git commit -m "$COMMIT_MESSAGE"
        
        # Push to remote with upstream tracking
        echo "Pushing to origin and setting upstream tracking..."
        git push -u origin "$BRANCH_NAME"
        
        echo "Branch '$BRANCH_NAME' has been pushed to origin with tracking."
    else
        echo "No commit message provided. Skipping commit."
    fi
else
    echo "Skipping initial commit. You can commit changes later."
fi

echo "Success! You are now on branch: $BRANCH_NAME"
echo "Ready to start working!"