#!/bin/bash

source "/var/local/redmine/update-repositories.env"

if [ -z "$REDMINE_API_KEY" ]; then
	echo -e "Environment variable 'REDMINE_API_KEY' is missing, ignoring."
	exit 0
fi

if [ -z "$GIT_SYNC_FOLDER" ]; then
	echo -e "Environment variable 'GIT_SYNC_FOLDER' is missing, ignoring."
	exit 0
fi

if [ ! -d "$GIT_SYNC_FOLDER" ]; then
	echo -e "Cannot find repositories storage: $GIT_SYNC_FOLDER"
	exit 1
fi

GIT=`command -v git`
if [ -z "$GIT" ]; then
	echo -e "Command 'git' is missing, failing."
	exit 1
fi

for REPO_DIR in "$GIT_SYNC_FOLDER/"*; do
	if [ -d "$REPO_DIR" ] && [[ "$REPO_DIR" =~ ^.+\.git$ ]]; then
		echo "Fetching $REPO_DIR"
		(cd "$REPO_DIR" && git remote update --prune) >> /dev/null
	fi
done

#/usr/src/redmine/bin/rails runner "Repository.fetch_changesets" -e production
curl -q "http://localhost:3000/sys/fetch_changesets?key=${REDMINE_API_KEY}"
