#!/bin/bash

while true; do
  # Make DATA directory at root directory
  mkdir -p /DATA
  
  # 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 [ ! -d "repo" ]; then
    echo "Repository $REPO_URL doesn't exist locally - Downloading..."
    git clone $REPO_URL repo
    cd repo
    rsync -av --delete --exclude '.git/' ./ /DATA
    curl -d "Repository $REPO_URL doesn't exist locally - Downloading..." $NTFY_URL
  fi

  # 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"
  elif [ $LOCAL = $BASE ]; then
      echo "Pulling Updates from Repository..."
      git pull origin main
      rsync -av --delete --exclude '.git/' ./ /DATA
      curl -d "$REPO_URL Automatically Pulled Update" $NTFY_URL
  else
      echo "Data Diverged - How exactly did this happen?"
  fi

  # Wait for 5 seconds before the next iteration
  sleep 5

done