#!/bin/bash

# Configuration
[[ "x${GITMONITOR_URLS}" == "x" ]] && GITMONITOR_URLS="/opt/src/repository.list"
[[ "x${GITMONITOR_LOCAL_PATH}" == "x" ]] && GITMONITOR_LOCAL_PATH="/opt/src"
[[ "x${GITMONITOR_BRANCH_NAME}" == "x" ]] && GITMONITOR_BRANCH_NAME="develop"
[[ "x${GITMONITOR_POLL_INTERVAL}" == "x" ]] && GITMONITOR_POLL_INTERVAL=60  # Seconds between checks
[[ "x${GITMONITOR_LOCK_FILE}" == "x" ]] && GITMONITOR_LOCK_FILE="/run/lock/git-monitor.lock" # File to prevent multiple instances

IFS="|"

# Functions
log_message() {
  local level=$1
  local message=$2
  timestamp=$(date +'%Y-%m-%d %H:%M:%S')
  #echo "$timestamp [$level] $message" >> "$LOG_FILE"
  echo "$timestamp [$level] $message"  # Also print to console (optional)
}

check_lock() {
  if [ -f "$GITMONITOR_LOCK_FILE" ]; then
    log_message "WARN" "Another instance is already running. Exiting."
    exit 1
  fi
}

create_lock() {
  touch "$GITMONITOR_LOCK_FILE"
}

run_after() {
  local after_pull_script=$1
  source $after_pull_script
}

initialize_repos() {
  while read -r repo_name repo_url; do
    if [ ! -d "$GITMONITOR_LOCAL_PATH/$repo_name" ]; then
      log_message "INFO" "Repository directory $GITMONITO_LOCAL_PATH/$repo_name does not exist. Cloning..."
      mkdir -p "$GITMONITOR_LOCAL_PATH/$repo_name"
      git clone --depth 1 "$repo_url" "$GITMONITOR_LOCAL_PATH/$repo_name"
      if [ $? -ne 0 ]; then
        log_message "ERROR" "Failed to clone repository. Exiting."
        exit 1
      fi
      log_message "INFO" "Repository cloned successfully."
    fi
  done <$GITMONITOR_URLS
}

check_for_updates() {
  local repo_name=$1
  local last_commit_hash
  local current_commit_hash

  # Get the last known commit hash (from a file)
  cd "$GITMONITOR
_LOCAL_PATH/$repo_name"
  if [ -f "$GITMONITOR_LOCAL_PATH/$repo_name/.git-monitor-last-commit" ]; then
    last_commit_hash=$(cat "$GITMONITOR_LOCAL_PATH/$repo_name/.git-monitor-last-commit")
  else
    last_commit_hash="" # Initialize if file doesn't exist
  fi

  # Fetch the latest commit hash from the remote repository
  git -C "$GITMONITOR_LOCAL_PATH/$repo_name" fetch origin $GITMONITOR_BRANCH_NAME
  current_commit_hash=$(git -C "$GITMONITOR_LOCAL_PATH/$repo_name" rev-parse origin $GITMONITOR_BRANCH_NAME)

  if [ -z "$last_commit_hash" ] || [ "$current_commit_hash" != "$last_commit_hash" ]; then
    log_message "INFO" "New commits detected. Pulling..."
    git -C "$GITMONITOR
  _LOCAL_PATH/$repo_name" pull origin $GITMONITOR_BRANCH_NAME
    if [ $? -eq 0 ]; then
      log_message "INFO" "Pull successful."

      # run local scripts
      if [ -f "$GITMONITOR_LOCAL_PATH/$repo_name/.git-monitor_after.sh" ]; then
        run_after "$GITMONITOR_LOCAL_PATH/$repo_name/.git-monitor_after.sh"
      fi
    
      # Update the last commit hash file
      echo "$current_commit_hash" > "$GITMONITOR_LOCAL_PATH/$repo_name/.git-monitor-last-commit"
    else
      log_message "ERROR" "Pull failed."
    fi
  fi
}

# Main Execution

trap 'rm -f $GITMONITOR_LOCK_FILE' EXIT

check_lock
create_lock

log_message "INFO" "Git monitor started."

initialize_repos

while true; do
  while read -r repo_name repo_url; do
    check_for_updates $repo_name
  done < $GITMONITOR_URLS
  sleep "$GITMONITOR_POLL_INTERVAL"
done

