#!/usr/bin/env bash

set -euo pipefail

COMMIT_MESSAGE="${1:-Update staging}"

echo "1/8 Checking repository..."
git rev-parse --is-inside-work-tree > /dev/null

CURRENT_BRANCH=$(git branch --show-current)

if [ "$CURRENT_BRANCH" != "staging" ]; then
    echo "Error: You must run this script from the staging branch."
    echo "Current branch: $CURRENT_BRANCH"
    exit 1
fi

echo "2/8 Saving local changes..."
git add -A

if ! git diff --cached --quiet; then
    git commit -m "$COMMIT_MESSAGE"
else
    echo "No new changes to commit."
fi

echo "3/8 Updating staging..."
git fetch origin
git rebase origin/staging

echo "4/8 Pushing staging..."
git push origin staging

echo "5/8 Updating main..."
git switch main
git pull --ff-only origin main

echo "6/8 Merging staging into main..."
git merge --no-ff staging -m "Merge staging into main"

echo "7/8 Pushing main..."
git push origin main

echo "8/8 Returning to staging and verifying..."
git switch staging
git fetch origin

LOCAL_STAGING=$(git rev-parse staging)
REMOTE_STAGING=$(git rev-parse origin/staging)
LOCAL_MAIN=$(git rev-parse main)
REMOTE_MAIN=$(git rev-parse origin/main)

echo
echo "Local staging:  $LOCAL_STAGING"
echo "Remote staging: $REMOTE_STAGING"
echo "Local main:     $LOCAL_MAIN"
echo "Remote main:    $REMOTE_MAIN"
echo

if [ "$LOCAL_STAGING" = "$REMOTE_STAGING" ] &&
   [ "$LOCAL_MAIN" = "$REMOTE_MAIN" ]; then
    echo "SUCCESS: staging and main are fully synchronized."
else
    echo "WARNING: Branches are not fully synchronized."
    exit 1
fi

git status
