#!/usr/bin/env bash
set -euo pipefail

WORK_TREE="/home/file/public_html/b"
GIT_DIR="/home/file/.git-building-management"
REMOTE="https://github.com/ahmad75naraghi/Building_Management.git"
BRANCH="main"

if [ ! -d "$WORK_TREE" ]; then
    echo "ERROR: Work tree does not exist: $WORK_TREE"
    exit 1
fi

if [ ! -d "$GIT_DIR" ]; then
    mkdir -p "$GIT_DIR"
    git --git-dir="$GIT_DIR" --work-tree="$WORK_TREE" init
    git --git-dir="$GIT_DIR" remote add origin "$REMOTE"
else
    git --git-dir="$GIT_DIR" remote set-url origin "$REMOTE" 2>/dev/null || \
    git --git-dir="$GIT_DIR" remote add origin "$REMOTE"
fi

git --git-dir="$GIT_DIR" --work-tree="$WORK_TREE" config user.name "ahmad75naraghi"
git --git-dir="$GIT_DIR" --work-tree="$WORK_TREE" config user.email "ahmad75naraghi@users.noreply.github.com"

git --git-dir="$GIT_DIR" --work-tree="$WORK_TREE" add -A

if ! git --git-dir="$GIT_DIR" --work-tree="$WORK_TREE" diff --cached --quiet; then
    git --git-dir="$GIT_DIR" --work-tree="$WORK_TREE" commit -m "Update Building Management"
fi

git --git-dir="$GIT_DIR" --work-tree="$WORK_TREE" branch -M "$BRANCH"

# Force push: GitHub main will be replaced by the contents of /home/file/public_html/b
git --git-dir="$GIT_DIR" --work-tree="$WORK_TREE" push -u origin "$BRANCH" --force

echo "PUSH completed successfully."