#!/bin/sh

while true; do
  # Set Git credentials
  git config --global credential.helper 'store --file /tmp/git-credentials'
  echo "url=$REPO_URL" > /tmp/git-credentials
  echo "username=$GIT_USERNAME" >> /tmp/git-credentials
  echo "password=$GIT_PASSWORD" >> /tmp/git-credentials

  # Navigate to the watcher directory
  cd /root/Repo_Watcher

  # Clone the repo if it doesn't exist
  if [ -z "$(find /root/Repo_Watcher/repo -maxdepth 1 -mindepth 1 -type f -o -type d 2>/dev/null)" ]; then
    curl -d "Pulling: $REPO_URL" $NTFY_URL
    echo "Pulling: $REPO_URL"
    git clone $REPO_URL repo
    cd repo
    rsync -av --delete --exclude '.git/' ./ /DATA
  fi

  cd repo

  # Fetch the latest changes
  git fetch origin main

  # Check if the local repository is behind the remote
  LOCAL=$(git rev-parse @)
  REMOTE=$(git rev-parse @{u})
  BASE=$(git merge-base @ @{u})

  if [ $LOCAL = $REMOTE ]; then
      echo "Repository Up-to-Date"
  else
      curl -d "Pulling: $REPO_URL" $NTFY_URL
      echo "Pulling: $REPO_URL"
      git pull origin main
      rsync -av --delete --exclude '.git/' ./ /DATA
  fi

  # Wait for 5 seconds before the next iteration
  sleep 5

done