#!/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="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
COMMON_SCRIPT="$SCRIPT_DIR/bulk-common"
if [[ ! -f "$COMMON_SCRIPT" ]]; then
    echo "Error: required script not found: $COMMON_SCRIPT" >&2
    exit 1
fi
# shellcheck source=/dev/null
source "$COMMON_SCRIPT"
bulk_init "$@"

# copy changes to the moonsunsoft repo
otoolbox run update --tags odoonix >> "$LOG_FILE" 2>&1
otoolbox repo sync-shielded >> "$LOG_FILE" 2>&1


GIT_BIN="$(command -v git)"
#For each folder in moonsun (it must be part of a shielded project)
for dir in "$WORKDIR/moonsunsoft"/*/; do
    if [ -d "$dir" ]; then
        project=$(basename "$dir")
        echo "Processing project: $project"
        echo "push changes to moonsunsoft/$project" >> "$LOG_FILE" 2>&1
        cd "$WORKDIR/moonsunsoft/$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
