#!/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"

echo "== Git 2: PULL =="

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

if [ ! -d "$GIT_DIR" ]; then
    echo "ERROR: Separate Git repository is not initialized."
    echo "Run git2_push.sh once first."
    exit 1
fi

echo "Fetching from GitHub..."

git --git-dir="$GIT_DIR" fetch origin "$BRANCH"

echo "Updating local branch..."

git --git-dir="$GIT_DIR" --work-tree="$WORK_TREE" checkout -B "$BRANCH" "origin/$BRANCH"

echo "Syncing files..."

git --git-dir="$GIT_DIR" --work-tree="$WORK_TREE" reset --hard "origin/$BRANCH"

echo "Removing files that no longer exist in GitHub..."

git --git-dir="$GIT_DIR" --work-tree="$WORK_TREE" clean -fd

echo
echo "================================"
echo "PULL completed successfully."
echo "================================"