#!/bin/bash
#############################################################################
#                                                                           #
# This file is part of the "ubuntu" module of the otoolbox project.         #
#                                                                           #
# This script is open-source and intended for automation purposes.          #
# It is distributed in the hope that it will be useful, but WITHOUT         #
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY        #
# or FITNESS FOR A PARTICULAR PURPOSE.                                      #
#                                                                           #
# Use of this script is entirely at your own risk.                          #
#                                                                           #
# Copyright (c) The otoolbox contributors.                                  #
#############################################################################
SCRIPT_DIR="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"
source "$SCRIPT_DIR/bulk-common"
cd "$WORKSPACE_ROOT" || { echo "Error: failed to change directory to $WORKSPACE_ROOT" >&2; exit 1; }


# Pull all
for dir in "$WORKDIR/$SHIELDED_ORGANIZATION"/*; do
    if [ -d "$dir" ]; then
        project=$(basename "$dir")
        echo "Pull project: $project"
        cd "$dir"
        git config --global --add safe.directory "$dir"
        # commit and push changes
        git pull >> "$LOG_FILE" 2>&1
    fi
done


# copy changes to the shielded organization repo
echo "Current directory is: $CURRENT_DIR"
echo "Copying changes to $SHIELDED_ORGANIZATION repository..."
cd "$WORKSPACE_ROOT"
otoolbox repo sync-shielded > "$LOG_FILE" 2>&1

# Push all
for dir in "$WORKSPACE_ROOT/$SHIELDED_ORGANIZATION"/*; do
    if [ -d "$dir" ]; then
        project=$(basename "$dir")
        echo "Processing project: $project"
        echo "push changes to $SHIELDED_ORGANIZATION/$project" >> "$LOG_FILE" 2>&1
        cd "$dir"
        git config --global --add safe.directory "$dir"
        # commit and push changes
        git add . >> "$LOG_FILE" 2>&1
        git commit -m "[SYNC] Update to the latest release on $SYNC_DATE" >> "$LOG_FILE" 2>&1
        git push >> "$LOG_FILE" 2>&1
    fi
done