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

readonly REMOTE_NAME="otoolbox-server"
readonly CONFIGURATION_VARIABLES=(
    SERVER
    SERVER_PATH
    SSH_USER
    ORGANIZATION
    REPOSITORY
    WORKSPACE_ROOT
    VERBOSE
)

ORIGINAL_WORKING_DIR="$(pwd -P)"
declare -A RUNTIME_CONFIGURATION_SET=()
declare -A RUNTIME_CONFIGURATION_VALUE=()

ORGANIZATIONS_DISCOVERED=0
REPOSITORIES_DISCOVERED=0
REPOSITORIES_SYNCHRONIZED=0
REPOSITORIES_SKIPPED=0
REPOSITORIES_FAILED=0

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

Synchronize local Git repositories with matching repositories on an SSH server.

OPTIONS:
  --server HOST          Remote server IP address or hostname
  --path PATH            Base repository directory on the remote server
  --user USER            SSH username
  --organization NAME    Synchronize only one organization
  --repository NAME      Synchronize only one repository (requires --organization)
  --verbose              Enable verbose output
  --help, -h             Show this help message and exit

CONFIGURATION:
  SERVER, SERVER_PATH, SSH_USER, ORGANIZATION, REPOSITORY, WORKSPACE_ROOT, VERBOSE
  Configuration precedence is: command line, runtime environment, .env, defaults.
  The .env file is loaded from the current directory, WORKSPACE_ROOT, or beside
  this script, in that order, when present.

EXAMPLES:
  $(basename "$0") --server 192.168.1.100 \\
      --path /home/odoo/addons-19 --user odoo
  $(basename "$0") --organization odoonix --repository server-ux --verbose

EOF
}

function remember_runtime_configuration() {
    local variable

    for variable in "${CONFIGURATION_VARIABLES[@]}"; do
        if [[ -v "$variable" ]]; then
            RUNTIME_CONFIGURATION_SET["$variable"]=1
            RUNTIME_CONFIGURATION_VALUE["$variable"]="${!variable}"
        fi
    done
}

function restore_runtime_configuration() {
    local variable

    for variable in "${CONFIGURATION_VARIABLES[@]}"; do
        if [[ -n "${RUNTIME_CONFIGURATION_SET[$variable]:-}" ]]; then
            printf -v "$variable" '%s' "${RUNTIME_CONFIGURATION_VALUE[$variable]}"
        fi
    done
}

function find_env_file() {
    local candidate
    local -a candidates=(
        "$ORIGINAL_WORKING_DIR/.env"
        "${RUNTIME_CONFIGURATION_VALUE[WORKSPACE_ROOT]:-}/.env"
        "$SCRIPT_PATH/.env"
    )
    local -A seen=()

    for candidate in "${candidates[@]}"; do
        [[ -n "$candidate" && -z "${seen[$candidate]:-}" ]] || continue
        seen["$candidate"]=1
        if [[ -f "$candidate" ]]; then
            printf '%s\n' "$candidate"
            return 0
        fi
    done

    return 1
}

function load_configuration() {
    local env_file

    remember_runtime_configuration
    _ot_init_working_dir

    if env_file="$(find_env_file)"; then
        # shellcheck source=/dev/null
        source "$env_file"
        ENV_FILE="$env_file"
    else
        ENV_FILE=""
    fi

    restore_runtime_configuration

    SERVER="${SERVER:-}"
    SERVER_PATH="${SERVER_PATH:-}"
    SSH_USER="${SSH_USER:-}"
    ORGANIZATION="${ORGANIZATION:-}"
    REPOSITORY="${REPOSITORY:-}"
    WORKSPACE_ROOT="${WORKSPACE_ROOT-$ORIGINAL_WORKING_DIR}"
    VERBOSE="${VERBOSE-false}"
    DEBUG="${DEBUG:-false}"
}

function normalize_verbose() {
    case "$VERBOSE" in
        true|1|yes|YES)
            VERBOSE=true
            ;;
        false|0|no|NO|"")
            VERBOSE=false
            ;;
        *)
            _ot_log_error "Invalid VERBOSE value '$VERBOSE'; expected true or false."
            return 1
            ;;
    esac
}

function require_argument_value() {
    local option="$1"
    local value="${2:-}"

    if [[ -z "$value" || "$value" == --* ]]; then
        _ot_log_error "Missing value for $option."
        show_help >&2
        exit 2
    fi
}

function parse_arguments() {
    while [[ $# -gt 0 ]]; do
        case "$1" in
            --server)
                require_argument_value "$1" "${2:-}"
                SERVER="$2"
                shift 2
                ;;
            --path)
                require_argument_value "$1" "${2:-}"
                SERVER_PATH="$2"
                shift 2
                ;;
            --user)
                require_argument_value "$1" "${2:-}"
                SSH_USER="$2"
                shift 2
                ;;
            --organization)
                require_argument_value "$1" "${2:-}"
                ORGANIZATION="$2"
                shift 2
                ;;
            --repository)
                require_argument_value "$1" "${2:-}"
                REPOSITORY="$2"
                shift 2
                ;;
            --verbose)
                VERBOSE=true
                shift
                ;;
            --help|-h)
                show_help
                exit 0
                ;;
            *)
                _ot_log_error "Unknown argument: $1"
                show_help >&2
                exit 2
                ;;
        esac
    done
}

function validate_name() {
    local label="$1"
    local value="$2"

    if [[ "$value" == "." || "$value" == ".." || "$value" == */* || "$value" == *$'\n'* || "$value" == *$'\r'* ]]; then
        _ot_log_error "$label must be a single directory name."
        return 1
    fi
}

function validate_configuration() {
    local valid=true

    if [[ -z "$SERVER" ]]; then
        _ot_log_error "SERVER is required; set it in the environment, .env, or with --server."
        valid=false
    elif [[ ! "$SERVER" =~ ^(\[[0-9A-Fa-f:.]+\]|[a-zA-Z0-9][a-zA-Z0-9._-]*)$ ]]; then
        _ot_log_error "SERVER must be a valid hostname, IPv4 address, or bracketed IPv6 address."
        valid=false
    fi

    if [[ -z "$SSH_USER" ]]; then
        _ot_log_error "SSH_USER is required; set it in the environment, .env, or with --user."
        valid=false
    elif [[ ! "$SSH_USER" =~ ^[a-zA-Z0-9._-]+$ ]]; then
        _ot_log_error "SSH_USER contains invalid characters."
        valid=false
    fi

    if [[ -z "$SERVER_PATH" || "$SERVER_PATH" != /* ]]; then
        _ot_log_error "SERVER_PATH must be a non-empty absolute path."
        valid=false
    elif [[ "$SERVER_PATH" == *$'\n'* || "$SERVER_PATH" == *$'\r'* ]]; then
        _ot_log_error "SERVER_PATH contains invalid newline characters."
        valid=false
    fi

    if [[ -n "$REPOSITORY" && -z "$ORGANIZATION" ]]; then
        _ot_log_error "--repository requires an organization."
        valid=false
    fi

    [[ -z "$ORGANIZATION" ]] || validate_name "ORGANIZATION" "$ORGANIZATION" || valid=false
    [[ -z "$REPOSITORY" ]] || validate_name "REPOSITORY" "$REPOSITORY" || valid=false

    if [[ ! -d "$WORKSPACE_ROOT" ]]; then
        _ot_log_error "Workspace directory does not exist: $WORKSPACE_ROOT"
        valid=false
    else
        WORKSPACE_ROOT="$(cd "$WORKSPACE_ROOT" && pwd -P)"
    fi

    if [[ "$valid" != "true" ]]; then
        return 1
    fi

    while [[ "$SERVER_PATH" != "/" && "$SERVER_PATH" == */ ]]; do
        SERVER_PATH="${SERVER_PATH%/}"
    done

    _ot_log_debug "Configuration file: ${ENV_FILE:-<none>}"
    _ot_log_debug "Workspace root: $WORKSPACE_ROOT"
}

function is_git_repository() {
    git -C "$1" rev-parse --git-dir >/dev/null 2>&1
}

function discover_repositories() {
    local organization="$1"
    local organization_path="$WORKSPACE_ROOT/$organization"
    local candidate
    local repository_path

    DISCOVERED_REPOSITORIES=()

    if [[ -n "$REPOSITORY" ]]; then
        repository_path="$organization_path/$REPOSITORY"
        if [[ ! -d "$repository_path" ]]; then
            _ot_log_error "Repository does not exist: $organization/$REPOSITORY"
            ((REPOSITORIES_FAILED += 1))
            return 1
        fi
        if ! is_git_repository "$repository_path"; then
            _ot_log_error "Directory is not a Git repository: $organization/$REPOSITORY"
            ((REPOSITORIES_FAILED += 1))
            return 1
        fi
        DISCOVERED_REPOSITORIES+=("$repository_path")
        return 0
    fi

    if [[ ! -d "$organization_path" ]]; then
        _ot_log_error "Organization directory does not exist: $organization"
        ((REPOSITORIES_FAILED += 1))
        return 1
    fi

    for candidate in "$organization_path"/*; do
        [[ -d "$candidate" ]] || continue
        if is_git_repository "$candidate"; then
            DISCOVERED_REPOSITORIES+=("$candidate")
            _ot_log_info "Discovered repository: $candidate"
        else
            ((REPOSITORIES_SKIPPED += 1))
            _ot_log_info "Skipping non-Git directory: $candidate"
        fi
    done

    return 0
}

function discover_organizations() {
    local organization_path
    local organization

    DISCOVERED_ORGANIZATIONS=()

    if [[ -n "$ORGANIZATION" ]]; then
        organization_path="$WORKSPACE_ROOT/$ORGANIZATION"
        if [[ ! -d "$organization_path" ]]; then
            _ot_log_error "Organization directory does not exist: $ORGANIZATION"
            ((REPOSITORIES_FAILED += 1))
            return 1
        fi
        DISCOVERED_ORGANIZATIONS+=("$ORGANIZATION")
        return 0
    fi

    for organization_path in "$WORKSPACE_ROOT"/*; do
        [[ -d "$organization_path" ]] || continue
        organization="${organization_path##*/}"

        local has_repository=false
        local repository_path
        for repository_path in "$organization_path"/*; do
            [[ -d "$repository_path" ]] || continue
            if is_git_repository "$repository_path"; then
                has_repository=true
                break
            fi
        done

        if [[ "$has_repository" == "true" ]]; then
            DISCOVERED_ORGANIZATIONS+=("$organization")
            _ot_log_info "Discovered organization: $organization"
        else
            _ot_log_info "Skipping organization without Git repositories: $organization"
        fi
    done

    return 0
}

function find_matching_remote() {
    local repository_path="$1"
    local target_url="$2"
    local remote_name
    local remote_url

    MATCHING_REMOTE=""
    while IFS= read -r remote_name; do
        [[ -n "$remote_name" ]] || continue
        while IFS= read -r remote_url; do
            if [[ "$remote_url" == "$target_url" ]]; then
                MATCHING_REMOTE="$remote_name"
                return 0
            fi
        done < <(git -C "$repository_path" remote get-url --push --all "$remote_name" 2>/dev/null || true)
    done < <(git -C "$repository_path" remote)

    return 1
}

function print_command() {
    local part
    printf 'git -C %q' "$1"
    shift
    for part in "$@"; do
        printf ' %q' "$part"
    done
    printf '\n'
}

function configure_remote() {
    local repository_path="$1"
    local target_url="$2"
    local configured_remote="$REMOTE_NAME"
    local existing_remote
    local existing_url=""

    if [[ "$VERBOSE" == "true" ]]; then
        _ot_log_info "Existing remotes for $repository_path:"
        git -C "$repository_path" remote -v
    fi

    if find_matching_remote "$repository_path" "$target_url"; then
        configured_remote="$MATCHING_REMOTE"
        _ot_log_info "Reusing remote '$configured_remote' for $target_url"
    else
        while IFS= read -r existing_remote; do
            if [[ "$existing_remote" == "$REMOTE_NAME" ]]; then
                existing_url="$(git -C "$repository_path" remote get-url --push "$REMOTE_NAME" 2>/dev/null || true)"
                _ot_log_error "Remote '$REMOTE_NAME' already points to '${existing_url:-<unknown>}' instead of '$target_url'."
                return 1
            fi
        done < <(git -C "$repository_path" remote)

        _ot_log_info "Creating remote '$REMOTE_NAME' for $target_url"
        if [[ "$VERBOSE" == "true" ]]; then
            _ot_log_info "Executing: $(print_command "$repository_path" remote add "$REMOTE_NAME" "$target_url")"
        fi
        if ! git -C "$repository_path" remote add "$REMOTE_NAME" "$target_url"; then
            _ot_log_error "Unable to create remote '$REMOTE_NAME' in $repository_path."
            return 1
        fi
        configured_remote="$REMOTE_NAME"
    fi

    CONFIGURED_REMOTE="$configured_remote"
    return 0
}

function push_repository() {
    local repository_path="$1"
    local organization="$2"
    local repository="$3"
    local target_url="${SSH_USER}@${SERVER}:${SERVER_PATH%/}/$organization/$repository"
    local current_branch

    _ot_log_info "Repository path: $repository_path"
    _ot_log_info "Remote URL: $target_url"

    if ! current_branch="$(git -C "$repository_path" symbolic-ref --quiet --short HEAD 2>/dev/null)"; then
        _ot_log_error "Cannot push $organization/$repository: HEAD is detached."
        return 1
    fi
    if ! git -C "$repository_path" rev-parse --verify HEAD >/dev/null 2>&1; then
        _ot_log_error "Cannot push $organization/$repository: the current branch '$current_branch' has no commits."
        return 1
    fi

    if ! configure_remote "$repository_path" "$target_url"; then
        return 1
    fi

    _ot_log_info "Pushing all local branches from $organization/$repository to '$CONFIGURED_REMOTE'."
    if [[ "$VERBOSE" == "true" ]]; then
        _ot_log_info "Executing: $(print_command "$repository_path" push "$CONFIGURED_REMOTE" --all)"
    fi
    if ! git -C "$repository_path" push "$CONFIGURED_REMOTE" --all; then
        _ot_log_error "Git push of branches failed for $organization/$repository; the original Git error is shown above."
        return 1
    fi

    if [[ "$VERBOSE" == "true" ]]; then
        _ot_log_info "Executing: $(print_command "$repository_path" push "$CONFIGURED_REMOTE" --tags)"
    fi
    if ! git -C "$repository_path" push "$CONFIGURED_REMOTE" --tags; then
        _ot_log_error "Git push of tags failed for $organization/$repository; the original Git error is shown above."
        return 1
    fi

    VERBOSE=true _ot_log_info "Synchronized $organization/$repository using remote '$CONFIGURED_REMOTE'."
    return 0
}

function show_summary() {
    VERBOSE=true _ot_log_info "Synchronization summary"
    VERBOSE=true _ot_log_info "Organizations discovered: $ORGANIZATIONS_DISCOVERED"
    VERBOSE=true _ot_log_info "Repositories discovered: $REPOSITORIES_DISCOVERED"
    VERBOSE=true _ot_log_info "Repositories synchronized: $REPOSITORIES_SYNCHRONIZED"
    VERBOSE=true _ot_log_info "Repositories skipped: $REPOSITORIES_SKIPPED"
    VERBOSE=true _ot_log_info "Repositories failed: $REPOSITORIES_FAILED"
}

for argument in "$@"; do
    if [[ "$argument" == "--help" || "$argument" == "-h" ]]; then
        show_help
        exit 0
    fi
done

load_configuration
parse_arguments "$@"

if ! normalize_verbose; then
    show_summary
    exit 2
fi

if ! validate_configuration; then
    show_summary
    exit 2
fi

if ! discover_organizations; then
    show_summary
    exit 1
fi

ORGANIZATIONS_DISCOVERED=${#DISCOVERED_ORGANIZATIONS[@]}

for organization in "${DISCOVERED_ORGANIZATIONS[@]}"; do
    _ot_log_info "Processing organization: $organization"

    if ! discover_repositories "$organization"; then
        continue
    fi

    if [[ ${#DISCOVERED_REPOSITORIES[@]} -eq 0 ]]; then
        _ot_log_warning "No Git repositories found for organization: $organization"
        ((REPOSITORIES_SKIPPED += 1))
        continue
    fi

    for repository_path in "${DISCOVERED_REPOSITORIES[@]}"; do
        repository="${repository_path##*/}"
        ((REPOSITORIES_DISCOVERED += 1))
        VERBOSE=true _ot_log_info "Synchronizing $organization/$repository"

        if push_repository "$repository_path" "$organization" "$repository"; then
            ((REPOSITORIES_SYNCHRONIZED += 1))
        else
            ((REPOSITORIES_FAILED += 1))
            _ot_log_error "Synchronization failed for $organization/$repository; continuing with remaining repositories."
        fi
    done
done

show_summary

if [[ "$REPOSITORIES_FAILED" -gt 0 ]]; then
    exit 1
fi
