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

# Resolve the script's directory, handling symlinks and aliases
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)"
}

# Load common functions and variables
SCRIPT_PATH=$(resolve_script_path)
source "$SCRIPT_PATH/otoolbox-common"
source "$SCRIPT_PATH/customer-common"

VERBOSE=false
DEBUG=false
POSITIONAL_ARGS=()

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

Update a customer repository and its git submodules to the latest version.

OPTIONS:
  --help, -h      Show this help message and exit
  --verbose       Enable verbose output
  --debug         Enable debug mode
  --tag TAG       Commit tag: FIX (fix), UP (update), INIT (initialization),
                  or CP (checkpoint; development will continue)
  --task KEY      Task key from the Moonsun task manager
  --message, -m MESSAGE
                  Commit message

Missing commit details are requested interactively.
EOF
}

function require_option_value() {
    if [[ $# -lt 2 || "$2" == -* ]]; then
        echo "Option $1 requires a value." >&2
        exit 2
    fi
}

function read_commit_detail() {
    local variable="$1" prompt="$2" value
    while [[ ! "${!variable}" =~ [^[:space:]] ]]; do
        if [[ ! -t 0 ]]; then
            echo "Missing $variable; an interactive terminal is required." >&2
            return 1
        fi
        if ! read -r -p "$prompt" value; then
            echo "Unable to read $variable." >&2
            return 1
        fi
        printf -v "$variable" '%s' "$value"
    done
}

function load_commit_details() {
    while true; do
        if [[ ! "$TASK_TAG" =~ [^[:space:]] && -t 0 ]]; then
            printf '%s\n' \
                'FIX: issue fixed; UP: update; INIT: initialization; CP: checkpoint.' >&2
        fi
        read_commit_detail TASK_TAG "Tag [FIX/UP/INIT/CP]: " || return 1
        case "$TASK_TAG" in
            FIX|UP|INIT|CP) break ;;
            *)
                echo "Invalid tag: $TASK_TAG. Choose FIX, UP, INIT, or CP." >&2
                if [[ ! -t 0 ]]; then
                    return 1
                fi
                TASK_TAG=""
                ;;
        esac
    done
    read_commit_detail TASK_KEY "Moonsun task key: " || return 1
    read_commit_detail MESSAGE "Commit message: " || return 1
}

TASK_TAG=""
TASK_KEY=""
MESSAGE=""
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
            ;;
        --task)
            require_option_value "$@"
            TASK_KEY="$2"
            shift 2
            ;;
        --tag)
            require_option_value "$@"
            TASK_TAG="$2"
            shift 2
            ;;
        --message|-m)
            require_option_value "$@"
            MESSAGE="$2"
            shift 2
            ;;
        --)
            shift
            while [[ $# -gt 0 ]]; do
                POSITIONAL_ARGS+=("$1")
                shift
            done
            break
            ;;
        -*)
            echo "Unknown option: $1" >&2
            show_help >&2
            exit 2
            ;;
        *)
            POSITIONAL_ARGS+=("$1")
            shift
            ;;
    esac
done

_ot_init

customer_load_working_dir "${POSITIONAL_ARGS[@]}"
customer_init_working_dir "$CUSTOMER_DIR"
customer_load_env_file "$CUSTOMER_DIR"


load_commit_details


cd "$CUSTOMER_DIR"
customer_print_info

# Prompt user for confirmation before proceeding
if [ -t 0 ]; then
    CURRENT_BRANCH="$(git -C "$CUSTOMER_DIR" rev-parse --abbrev-ref HEAD 2>/dev/null || echo "unknown")"
    _ot_log_info "About to update customer software in '$CUSTOMER_DIR' (branch: $CURRENT_BRANCH)."
    read -r -p "Are you sure you want to continue? [y/N] " answer
    case "$answer" in
        [Yy]|[Yy][Ee][Ss]) ;;
        *) _ot_log_info "Aborted by user." >&2; exit 0 ;;
    esac
else
    echo "No interactive terminal detected. Aborting — confirmation required." >&2
    exit 1
fi



_ot_log_debug "Starting customer update process in directory: $CUSTOMER_DIR"
_ot_run_as_worker git pull
_ot_run_as_worker git submodule update --remote
_ot_run_as_worker git add -A
_ot_run_as_worker git commit -m "[$TASK_TAG][$TASK_KEY] $MESSAGE"
_ot_run_as_worker git push
