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



########################################################################################
#                                 Pre-requisites                                       #
########################################################################################
# maso, 2025: check if the current directory is workspace root. The workspace
# root is the dirctory that contains the .venv/bin/bulk-pull.sh script (current script).
# If not, change the current directory to the workspace root.
#
# The script may be a symbol link, we need to resolve the symbol link to get the actual
# directory of the script.
# We must store current direcotry before changing it to the workspace root, because
# we need to return to the original directory after pulling changes from the
# repositories even there is error.
########################################################################################

function customer_select_repository() {
    local selected=0
    local key=""
    local sequence=""
    local i=""

    while true; do
        printf "Available repositories:\n" >&2
        for i in "${!repos[@]}"; do
            if (( i == selected )); then
                printf "  > %s\n" "${repos[i]}" >&2
            else
                printf "    %s\n" "${repos[i]}" >&2
            fi
        done
        printf "Use the Up/Down arrow keys and press Enter to select (q to abort).\n" >&2

        if ! IFS= read -r -s -n 1 key; then
            printf "\n" >&2
            return 1
        fi

        if [[ "$key" == $'\x1b' ]]; then
            sequence=""
            if IFS= read -r -s -n 2 -t 0.1 sequence; then
                case "$sequence" in
                    "[A")
                        selected=$(( (selected - 1 + ${#repos[@]}) % ${#repos[@]} ))
                        ;;
                    "[B")
                        selected=$(( (selected + 1) % ${#repos[@]} ))
                        ;;
                esac
            fi
        elif [[ -z "$key" ]]; then
            printf '%s\n' "$CUSTOMER_ROOT_DIR/${repos[selected]}"
            printf "\n" >&2
            return 0
        elif [[ "$key" == "q" || "$key" == "Q" ]]; then
            printf "\n" >&2
            return 1
        fi

        printf "\033[%dA\r\033[J" "$(( ${#repos[@]} + 1 ))" >&2
    done
}


function customer_get_root_dir() {
    if [[ -n "${CUSTOMER_ROOT_DIR-}" ]]; then
        if [[ ! -d "$CUSTOMER_ROOT_DIR" ]]; then
            echo "Error: CUSTOMER_ROOT_DIR is set but is not a directory: $CUSTOMER_ROOT_DIR" >&2
            return 1
        fi
        if [[ -z "$SCRIPT_DIR" ]]; then
            echo "Error: cannot resolve absolute path of CUSTOMER_ROOT_DIR: $CUSTOMER_ROOT_DIR" >&2
            return 1
        fi
        printf '%s\n' "$CUSTOMER_ROOT_DIR"
    else
        pwd
    fi
}


function customer_load_working_dir() {
    CUSTOMER_ROOT_DIR=$(customer_get_root_dir) || exit 1



    if [[ $# -lt 1 ]]; then

        # discover all org/repo directories (exactly two levels deep) that are git repositories
        mapfile -t _candidate_paths < <(find "$CUSTOMER_ROOT_DIR" -mindepth 2 -maxdepth 2 -type d -print 2>/dev/null | sort)

        repos=()
        for _p in "${_candidate_paths[@]}"; do
            # relative form ORG/REPO
            rel="${_p#"$CUSTOMER_ROOT_DIR"/}"
            # ensure it's a git repository
            if [[ -d "$_p/.git" ]] || git -C "$_p" rev-parse --git-dir >/dev/null 2>&1; then
                repos+=("$rel")
            fi
        done

        if [[ ${#repos[@]} -eq 0 ]]; then
            echo "Error: no repositories found under $CUSTOMER_ROOT_DIR" >&2
            exit 1
        fi

        # if only one repo, select it automatically
        if [[ ${#repos[@]} -eq 1 ]]; then
            REPO_INPUT="${repos[0]}"
            ORG="${REPO_INPUT%%/*}"
            REPO="${REPO_INPUT##*/}"
            CLONE_URL="git@github.com:${ORG}/${REPO}.git"
            CUSTOMER_DIR="$CUSTOMER_ROOT_DIR/$ORG/$REPO"
        else
            CUSTOMER_DIR=$(customer_select_repository) || {
                echo "Aborted."
                exit 1
            }

            ORG=$(basename "$(dirname "$CUSTOMER_DIR")")
            REPO=$(basename "$CUSTOMER_DIR")
            CLONE_URL="git@github.com:${ORG}/${REPO}.git"
        fi


    else
        REPO_INPUT="$1"
        ORG=""
        REPO=""
        CLONE_URL=""
        if [[ "$REPO_INPUT" =~ ^git@github\.com:([^/]+)/([^/]+)\.git$ ]]; then
            ORG="${BASH_REMATCH[1]}"
            REPO="${BASH_REMATCH[2]}"
            CLONE_URL="$REPO_INPUT"
        elif [[ "$REPO_INPUT" =~ ^([^/]+)/([^/]+)$ ]]; then
            ORG="${BASH_REMATCH[1]}"
            REPO="${BASH_REMATCH[2]}"
            CLONE_URL="git@github.com:${ORG}/${REPO}.git"
        else
            echo "Error: invalid repository format." >&2
            exit 1
        fi
        CUSTOMER_DIR="$CUSTOMER_ROOT_DIR/$ORG/$REPO"
    fi

    # CUSTOMER_ROOT_DIR must not be one of SCRIPT_DIR or WORKSPACE_ROOT
    if [[ "$CUSTOMER_ROOT_DIR" == "$SCRIPT_DIR" ]]; then
        echo "$SCRIPT_DIR"
        echo "Error: CUSTOMER_ROOT_DIR cannot be the same as SCRIPT_DIR: $SCRIPT_DIR" >&2
        exit 1
    fi
    if [[ "$CUSTOMER_ROOT_DIR" == "$WORKSPACE_ROOT" ]]; then
        echo "$WORKSPACE_ROOT"
        echo "Error: CUSTOMER_ROOT_DIR cannot be the same as WORKSPACE_ROOT: $WORKSPACE_ROOT" >&2
        exit 1
    fi

    # add save working directory to global safe.directory config to avoid git warnings and errors
    # when running as different users
    if ! git config --global --get-all safe.directory | grep -qxF "$CUSTOMER_DIR"; then
        git config --global --add safe.directory "$CUSTOMER_DIR"
    fi
    if ! _ot_run_as_worker git config --global --get-all safe.directory | grep -qxF "$CUSTOMER_DIR"; then
        _ot_run_as_worker git config --global --add safe.directory "$CUSTOMER_DIR"
    fi

}



function customer_init_working_dir() {
    # Check if there is moonsun.env file in the current directory.
    CUSTOMER_DIR="$1"
    if [[ ! -f "$CUSTOMER_DIR/moonsun.env" ]]; then
        _ot_log_warning "moonsun.env not found. The current folder may not be a Moonsun customer."
        read -r -p "Are you sure this is a customer folder and you want to create this file? (y/N): " CONFIRM
        if [[ "$CONFIRM" == "y" || "$CONFIRM" == "Y" ]]; then
            _ot_run_as_worker touch "$CUSTOMER_DIR/moonsun.env"
            _ot_log_info "Created moonsun.env"
        else
            _ot_log_error "Aborted."
            exit 1
        fi
    fi
}


function customer_load_env_file() {
    CUSTOMER_DIR="$1"
    if [[ -f "$CUSTOMER_DIR/moonsun.env" ]]; then
        source "$CUSTOMER_DIR/moonsun.env"
    else
        _ot_log_error "moonsun.env file not found in $CUSTOMER_DIR"
    fi
}


function customer_print_info() {
    # Load remote branch names
    export BRANCH=$(git -C "$CUSTOMER_DIR" branch -r 2>/dev/null | sed 's/^[ *]*//;s/ ->.*$//' | sort)
    export REMOTE_REPO=$(git remote -v)
    # Load current branch name of the repository
    CURRENT_BRANCH=$(git -C "$CUSTOMER_DIR" branch --show-current 2>/dev/null)
    if [[ -n "$CURRENT_BRANCH" ]]; then
        BRANCH="${BRANCH//$CURRENT_BRANCH/($CURRENT_BRANCH)}"
    fi
    echo "==================================================="
    echo "Customer Name   : $CUSTOMER_NAME"
    echo "Odoo Branch     : $CUSTOMER_BRANCH"
    echo "Working DIR     : $CUSTOMER_DIR"
    echo "Current Branch  : $CURRENT_BRANCH"
    echo "Branchs         : "
    echo "$BRANCH"
    echo "==================================================="
    echo "Remote Repositories:"
    echo "$REMOTE_REPO"
    echo "==================================================="
}
