#!/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.                                  #
#############################################################################
set -e

function resolve_script_path() {
    local source="${BASH_SOURCE[0]}"
    while [[ -L "$source" ]]; do
        local dir
        dir="$(cd -P "$(dirname "$source")" >/dev/null 2>&1 && pwd)"
        source="$(readlink "$source")"
        [[ $source != /* ]] && source="$dir/$source"
    done
    echo "$(cd -P "$(dirname "$source")" >/dev/null 2>&1 && pwd)"
}

SCRIPT_PATH=$(resolve_script_path)
source "$SCRIPT_PATH/otoolbox-common"

VERBOSE=false
DEBUG=false
NO_PULL=false

function show_help() {
    cat << EOF
Usage: $(basename "$0") [OPTIONS]

Sync shielded repositories and push generated updates.

OPTIONS:
  --help, -h      Show this help message and exit
  --verbose       Enable verbose output
  --debug         Enable debug mode
  --no-pull       Skip running otoolbox-pull before sync

EOF
}

while [[ $# -gt 0 ]]; do
    case "$1" in
        --help|-h)
            show_help
            exit 0
            ;;
        --verbose)
            export VERBOSE=true
            shift
            ;;
        --debug)
            export VERBOSE=true
            export DEBUG=true
            shift
            ;;
        --no-pull)
            NO_PULL=true
            shift
            ;;
        *)
            echo "Unknown option: $1" >&2
            show_help >&2
            exit 2
            ;;
    esac
done

_ot_init


function _sync_shilded_organization(){
    SHIELDED_ORGANIZATION=$1
    if [[ -z "$SHIELDED_ORGANIZATION" ]]; then
        _ot_log_error "SHIELDED_ORGANIZATION is not set."
        exit 1
    fi

    if [[ "$NO_PULL" != "true" ]]; then
        _ot_log_info "Running otoolbox-pull before sync..."
        pull_args=()
        [[ "$DEBUG" == "true" ]] && pull_args+=("--debug")
        [[ "$DEBUG" != "true" && "$VERBOSE" == "true" ]] && pull_args+=("--verbose")
        "$SCRIPT_PATH/otoolbox-pull" "${pull_args[@]}"
    else
        _ot_log_info "Skipping pull phase (--no-pull enabled)."
    fi

    _ot_run_as_worker otoolbox repo sync-shielded >> "$LOG_FILE" 2>&1

    for dir in "$WORKSPACE_ROOT/$SHIELDED_ORGANIZATION"/*/; do
        if [[ -d "$dir" ]]; then
            project="$(basename "$dir")"
            _ot_log_info "Processing project: $project"
            _ot_log_info "Pushing changes to $SHIELDED_ORGANIZATION/$project"

            _ot_run_as_worker git -C "$dir" pull >> "$LOG_FILE" 2>&1
            _ot_run_as_worker git -C "$dir" add . >> "$LOG_FILE" 2>&1
            _ot_run_as_worker git -C "$dir" commit -m "[SYNC] Update to the latest release on ${SYNC_DATE:-$(date +%Y-%m-%d)}" >> "$LOG_FILE" 2>&1 || true
            _ot_run_as_worker git -C "$dir" push >> "$LOG_FILE" 2>&1
        fi
    done
}




if [[ -z "${PROTECTED_ORGANIZATIONS-}" ]]; then
    _ot_log_error "PROTECTED_ORGANIZATIONS is not set. Please define it with one or more organization names."
    exit 1
fi

# convert to array (handles both single value and space-separated list)
read -r -a _protected_orgs <<< "$PROTECTED_ORGANIZATIONS"

for _org in "${_protected_orgs[@]}"; do
    _ot_log_info "Processing shielded organization: $_org"
    _sync_shilded_organization "$_org"
done
