# shellcheck shell=dash

___x_cmd_boot_alterdefault___parse_default_version(){
    local line
    while read -r line; do
        case "$line" in
            ___X_CMD_VERSION_DEFAULT=*)
                x_="${line#*=}"
                return 0
                ;;
            *)
                ;;
        esac
    done
    return 1
}

___x_cmd_boot_alterdefault(){
    case "$1" in
        -h|--help)  ___x_cmd help -m boot alterdefault ;    return ;;
        "")         ___x_cmd help -m boot alterdefault >&2; return 64 ;;
    esac

    local version="$1"
    local root="${2:-$___X_CMD_ROOT}"

    command chmod 700 "$root"   # Make sure the directory is only accessable for the current user ...

    if [ -f "$root/X" ]; then
        x_=;
        if ___x_cmd_boot_alterdefault___parse_default_version <"$root/X"; then
            if [ "$x_" = "$version" ]; then
                boot:info "Current version is already $version"
                return 0
            fi

            boot:info "Current default Version is $x_. Changing it to $version."
        fi
    fi

    boot:info "Update the $root/X"

    >"$root/X" printf "%s\n%s\n" \
    "___X_CMD_VERSION_DEFAULT=${version}"'
    if [ -n "$___X_CMD_ROOT" ] && [ ! -w "$___X_CMD_ROOT" ]; then
        printf "%s\n" \
            "- folder defined ___X_CMD_ROOT specified is not writable." \
            "  ___X_CMD_ROOT: $___X_CMD_ROOT" \
            "  ___X_CMD_VERSION: $___X_CMD_VERSION" \
            "  ___X_CMD_ROOT_CODE: $___X_CMD_ROOT_CODE" >&2
        ___X_CMD_ROOT=
        ___X_CMD_VERSION=
        ___X_CMD_ROOT_CODE=
    fi' \
    ". \"\${___X_CMD_ROOT:=$root}/v/\${___X_CMD_VERSION:=\${___X_CMD_VERSION_DEFAULT}}/X\""

}
