git-repo-updater/repo_watcher.sh
2024-09-10 05:33:04 -06:00

80 lines
2.9 KiB
Bash

#!/bin/sh
# Function to process each repo-destination pair
process_repo() {
FULL_REPO_URL=$1
DESTINATION=$2
# Extract the URL without credentials for logging and notifications
CLEAN_REPO_URL=$(echo "$FULL_REPO_URL" | sed 's/https:\/\/[^@]*@/https:\/\//')
# Directory to hold the repository locally
REPO_DIR="/srv/Repo_Cache/$(basename $CLEAN_REPO_URL .git)"
# Clone the repo if it doesn't exist, or navigate to it if it does
if [ ! -d "$REPO_DIR" ]; then
curl -d "Cloning: $CLEAN_REPO_URL" $NTFY_URL
git clone "$FULL_REPO_URL" "$REPO_DIR" > /dev/null 2>&1
fi
cd "$REPO_DIR" || exit
# Fetch the latest branch information
git fetch origin > /dev/null 2>&1
# List the available branches at the remote
AVAILABLE_BRANCHES=$(git ls-remote --heads origin | awk '{print $2}' | sed 's/refs\/heads\///')
# Detect the default branch dynamically (check for both 'main' and 'master')
if echo "$AVAILABLE_BRANCHES" | grep -q "^main$"; then
DEFAULT_BRANCH="main"
elif echo "$AVAILABLE_BRANCHES" | grep -q "^master$"; then
DEFAULT_BRANCH="master"
else
echo "Error: Neither 'main' nor 'master' branch exists in $FULL_REPO_URL"
exit 1
fi
# Check if the branch exists locally, and if not, create and set upstream
if ! git show-ref --verify --quiet refs/heads/$DEFAULT_BRANCH; then
git checkout -b $DEFAULT_BRANCH origin/$DEFAULT_BRANCH || exit 1
fi
# Check if an upstream is configured; if not, set it
if ! git rev-parse --abbrev-ref --symbolic-full-name @{u} > /dev/null 2>&1; then
git branch --set-upstream-to=origin/$DEFAULT_BRANCH $DEFAULT_BRANCH || exit 1
fi
# Fetch the latest changes from the correct branch
git fetch origin $DEFAULT_BRANCH > /dev/null 2>&1
# Check if the local repository is behind the remote
LOCAL=$(git rev-parse @)
REMOTE=$(git rev-parse @{u})
if [ "$LOCAL" != "$REMOTE" ]; then
curl -d "Updating: $CLEAN_REPO_URL" $NTFY_URL
git pull origin $DEFAULT_BRANCH > /dev/null 2>&1
rsync -av --delete --exclude '.git/' ./ "$DESTINATION" > /dev/null 2>&1
fi
}
# Main loop
while true; do
# Iterate over each environment variable matching 'REPO_[0-9]+'
env | grep '^REPO_[0-9]\+=' | while IFS='=' read -r name value; do
# Split the value by comma and read into separate variables
OLD_IFS="$IFS" # Save the original IFS
IFS=',' # Set IFS to comma for splitting
set -- $value # Set positional parameters ($1, $2, ...)
REPO_URL="$1" # Assign first parameter to REPO_URL
DESTINATION="$2" # Assign second parameter to DESTINATION
IFS="$OLD_IFS" # Restore original IFS
process_repo "$REPO_URL" "$DESTINATION"
done
# Wait for 30 seconds before the next iteration
sleep 30
done