#!/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]}")")"

print_help() {
    cat <<'EOF'
Usage: bulk-sync-shielded [OPTIONS]

Options:
  --no-pull    Skip running bulk-pull before syncing shielded repositories.
  --help       Show this help message and exit.
EOF
}

NO_PULL=0
for arg in "$@"; do
    case "$arg" in
        --help)
            print_help
            exit 0
            ;;
        --no-pull)
            NO_PULL=1
            ;;
        *)
            echo "Error: unknown option: $arg" >&2
            echo "Try '--help' for usage." >&2
            exit 1
            ;;
    esac
done

source "$SCRIPT_DIR/bulk-common"
cd "$WORKSPACE_ROOT" || { echo "Error: failed to change directory to $WORKSPACE_ROOT" >&2; exit 1; }

# copy changes to the shielded organization repo
if [ "$NO_PULL" -eq 0 ]; then
    bulk-pull
fi
otoolbox repo sync-shielded >> "$LOG_FILE" 2>&1


GIT_BIN="$(command -v git)"
#For each folder in the shielded organization (it must be part of a shielded project)
for dir in "$WORKDIR/$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 "$WORKDIR/$SHIELDED_ORGANIZATION/$project"
        # commit and push changes
        sudo -u "$WORKER_USER" -H "$GIT_BIN" pull >> "$LOG_FILE" 2>&1
        sudo -u "$WORKER_USER" -H "$GIT_BIN" add . >> "$LOG_FILE" 2>&1
        sudo -u "$WORKER_USER" -H "$GIT_BIN" commit -m "[SYNC] Update to the latest release on $SYNC_DATE" >> "$LOG_FILE" 2>&1
        sudo -u "$WORKER_USER" -H "$GIT_BIN" push >> "$LOG_FILE" 2>&1
    fi
done
