#!/usr/bin/env bash
# gitbash - Interactive git utilities for bash with fzf-powered menus

# Resolve symlinks to get the actual script location
SOURCE="${BASH_SOURCE[0]}"
# Started from Windows with C:\...\bin\gitbash: dirname needs forward slashes
[[ "$OSTYPE" == msys* || "$OSTYPE" == cygwin* ]] && SOURCE="${SOURCE//\\//}"
while [[ -L "$SOURCE" ]]; do
    DIR="$(cd -P "$(dirname "$SOURCE")" && pwd)"
    SOURCE="$(readlink "$SOURCE")"
    [[ "$SOURCE" != /* ]] && SOURCE="$DIR/$SOURCE"
done
SCRIPT_DIR="$(cd -P "$(dirname "$SOURCE")/.." && pwd)"
GITBASH_BIN="$SCRIPT_DIR/bin/gitbash"
# pnpm keeps each version in its own folder (node_modules/.pnpm/gitbash@X/node_modules/gitbash):
# run gitbash through the node_modules/gitbash link instead, which follows updates
if [[ "$SCRIPT_DIR" == */node_modules/.pnpm/gitbash@*/node_modules/gitbash &&
      -x "${SCRIPT_DIR%%/.pnpm/*}/gitbash/bin/gitbash" ]]; then
    GITBASH_BIN="${SCRIPT_DIR%%/.pnpm/*}/gitbash/bin/gitbash"
fi
COMMANDS_DIR="$SCRIPT_DIR/commands"
VERSION="$(grep -o '"version": *"[^"]*"' "$SCRIPT_DIR/package.json" | head -1 | cut -d'"' -f4)"
# Not exported: they would leak into git hooks, editors and merge tools.
# Commands are sourced into this process; nested runs of gitbash set them again.
export -n SCRIPT_DIR GITBASH_BIN VERSION
# Read from the environment (a parent gitbash sets them), but not passed on to
# git hooks, editors and merge tools either
export -n GITBASH_ASSUME_YES GITBASH_NESTED GB_COLOR 2>/dev/null

# shellcheck source=../commands/_utils.sh
source "$COMMANDS_DIR/_utils.sh"
# shellcheck source=../commands/_self_update.sh
source "$COMMANDS_DIR/_self_update.sh"

# Available commands
COMMANDS=(
    "branch"
    "cleanstash"
    "cleanup"
    "commit"
    "commits"
    "create"
    "pr"
    "repo"
    "reset-repo"
    "stale"
    "stash"
    "stashes"
    "status"
    "switch"
    "unstash"
    "update"
)

is_command() {
    local cmd
    for cmd in "${COMMANDS[@]}"; do
        [[ "$cmd" == "$1" ]] && return 0
    done
    return 1
}

# =============================================================================
# Configuration wizard
# =============================================================================

# key|type|question
SETTINGS=(
    "GITBASH_CREATE_BRANCH_PREFIX|prefix|Branch prefix inserted between type and branch name (e.g. 'team' → feature/team/PROJ-123-fix-bug)"
    "GITBASH_CREATE_NO_ISSUE_PARSING|inverted|Parse Jira issue numbers into branch names? (yes/no)"
    "GITBASH_CREATE_ISSUE_PARSING_FALLBACK|text|Fallback issue prefix when no issue number is given"
    "GITBASH_CREATE_AUTO_PUSH|yesno|Push new branches to the remote right after 'create'? (yes/no)"
    "GITBASH_MERGE_COMMAND|command|Merge tool opened by 'update' on conflicts (not allowed in the committed .gitbashrc)"
    "GITBASH_THEME|theme|Theme for delta/bat previews (auto/dark/light)"
    "GITBASH_STALE_MONTHS|number|Stale remote branch threshold in months (used by 'stale')"
    "GITBASH_CLEANUP_DAYS|number|Stale local branch threshold in days (used by 'cleanup')"
    "GITBASH_PROTECTED_BRANCHES|text|Branches never offered for deletion (space-separated globs)"
    "GITBASH_RESET_KEEP|text|Files kept by 'reset-repo' (space-separated .gitignore patterns, e.g. '.env .idea/')"
    "GITBASH_BASE_BRANCH|text|Base branch (empty = detect from the remote's HEAD, then main/master)"
    "GITBASH_REMOTE|text|Remote name"
    "GITBASH_NO_UPDATE_CHECKS|inverted|Check for gitbash updates now and then, and offer to install them? (yes/no)"
)

# Default value of a setting
setting_default() {
    case "$1" in
        GITBASH_CREATE_NO_ISSUE_PARSING) echo "no" ;;
        GITBASH_CREATE_ISSUE_PARSING_FALLBACK) echo "NOISSUE" ;;
        GITBASH_CREATE_AUTO_PUSH) echo "yes" ;;
        GITBASH_MERGE_COMMAND) echo "fork" ;;
        GITBASH_THEME) echo "auto" ;;
        GITBASH_STALE_MONTHS) echo "3" ;;
        GITBASH_CLEANUP_DAYS) echo "7" ;;
        GITBASH_PROTECTED_BRANCHES) echo "main master develop release/*" ;;
        GITBASH_REMOTE) echo "origin" ;;
        GITBASH_NO_UPDATE_CHECKS) echo "no" ;;
        *) echo "" ;;
    esac
}

# Value of a setting stored in a specific file. Returns 1 if not set there.
file_value() {
    local file="$1" key="$2" k v
    while IFS='=' read -r k v; do
        if [[ "$k" == "$key" ]]; then
            printf '%s' "$v"
            return 0
        fi
    done < <(_gb_config_entries "$file")
    return 1
}

# Convert between the stored value and what the wizard shows.
# GITBASH_CREATE_NO_ISSUE_PARSING and GITBASH_NO_UPDATE_CHECKS are stored inverted.
to_display() {
    local type="$1" value="$2"
    if [[ "$type" == "inverted" ]]; then
        [[ "$value" == "yes" ]] && echo "no" || echo "yes"
    else
        printf '%s' "$value"
    fi
}

# Validate an answer and print the value to store. Returns 1 if invalid.
to_stored() {
    local type="$1" answer="$2"
    if [[ "$answer" == *'"'* || "$answer" == *'$'* || "$answer" == *'`'* || "$answer" == *\\* ]]; then
        echo "Values cannot contain \", \$, \` or \\." >&2
        return 1
    fi
    case "$type" in
        inverted)
            case "$answer" in
                yes) echo "no" ;;
                no) echo "yes" ;;
                *) echo "Please answer yes or no." >&2; return 1 ;;
            esac
            ;;
        yesno)
            case "$answer" in
                yes|no) echo "$answer" ;;
                *) echo "Please answer yes or no." >&2; return 1 ;;
            esac
            ;;
        theme)
            case "$answer" in
                auto|dark|light) echo "$answer" ;;
                *) echo "Please answer auto, dark or light." >&2; return 1 ;;
            esac
            ;;
        number)
            if [[ "$answer" =~ ^[1-9][0-9]*$ ]]; then
                echo "$answer"
            else
                echo "Please enter a whole number of at least 1." >&2
                return 1
            fi
            ;;
        prefix)
            echo "${answer%/}"
            ;;
        *)
            echo "$answer"
            ;;
    esac
}

# Interactive configuration for one scope: global (~/.gitbashrc),
# local (<repo>/.gitbashrc, committed) or user (<repo>/.gitbashrc-user, not committed)
configure_wizard() {
    local scope="$1" file repo_root=""
    case "$scope" in
        global)
            file=$(gb_global_config_file)
            ;;
        local|user)
            if ! repo_root=$(git rev-parse --show-toplevel 2>/dev/null); then
                print_error "Not inside a git repository."
                return 1
            fi
            if [[ "$scope" == "local" ]]; then
                file="$repo_root/.gitbashrc"
            else
                file="$repo_root/.gitbashrc-user"
            fi
            ;;
    esac

    # Effective values from all config files, used as defaults
    gb_load_config 2>/dev/null

    echo "Configure gitbash ($scope) - writes to $file"
    if [[ "$scope" == "global" ]]; then
        echo "Press Enter to keep the current value, or '-' to reset it to the default."
    else
        echo "Press Enter to keep this file's current setting, '-' to remove the override,"
        echo "or '\"\"' to override with an empty value."
    fi
    echo

    local -a lines
    local entry key type question current default answer stored has_override shown n=0
    for entry in "${SETTINGS[@]}"; do
        n=$((n + 1))
        IFS='|' read -r key type question <<< "$entry"
        if [[ "$scope" == "local" ]]; then
            [[ "$key" == "GITBASH_MERGE_COMMAND" || "$key" == "GITBASH_NO_UPDATE_CHECKS" ]] && continue
        fi

        default=$(setting_default "$key")
        has_override=false
        if current=$(file_value "$file" "$key"); then
            has_override=true
        elif [[ "$scope" == "global" ]]; then
            current="$default"
        fi

        echo "$n. $question"
        if [[ "$scope" == "global" ]]; then
            shown=$(to_display "$type" "$current")
        else
            shown=$(to_display "$type" "${!key}")
            if [[ "$has_override" == true ]]; then
                echo "   Current override: '$(to_display "$type" "$current")'"
            else
                echo "   Current (inherited): '$shown'"
            fi
        fi

        while true; do
            if ! prompt_read "   Value [$shown]: " answer; then
                echo "Aborted - nothing was saved."
                return 1
            fi
            if [[ -z "$answer" ]]; then
                # Keep what this file has
                if [[ "$scope" == "global" || "$has_override" == true ]]; then
                    lines+=("$key=\"$current\"")
                fi
                break
            fi
            if [[ "$answer" == "-" ]]; then
                if [[ "$scope" == "global" ]]; then
                    lines+=("$key=\"$default\"")
                fi
                break
            fi
            [[ "$answer" == '""' ]] && answer=""
            if [[ -z "$answer" && "$type" != "prefix" && "$type" != "text" ]]; then
                echo "   This setting cannot be empty." >&2
                continue
            fi
            if stored=$(to_stored "$type" "$answer"); then
                lines+=("$key=\"$stored\"")
                break
            fi
        done
        echo
    done

    if [[ "$scope" != "global" && ${#lines[@]} -eq 0 ]]; then
        if [[ -f "$file" ]]; then
            rm -f "$file"
            print_info "No overrides left - removed $file"
        else
            print_info "No overrides configured."
        fi
        return 0
    fi

    local flag="--config"
    [[ "$scope" != "global" ]] && flag="--config-$scope"
    {
        echo "# gitbash configuration ($scope). Generated by 'gitbash $flag'."
        echo "# Only plain GITBASH_*=\"value\" lines are read; nothing in this file is executed."
        [[ "$scope" == "user" ]] && echo "# Personal settings - not committed (listed in .git/info/exclude)."
        echo
        local line
        for line in ${lines[@]+"${lines[@]}"}; do
            echo "$line"
        done
    } > "$file"
    print_success "Saved $file"

    if [[ "$scope" == "user" ]]; then
        exclude_user_config
    elif [[ "$scope" == "global" ]]; then
        check_dependencies
        check_shell_integration
    fi
}

# Keep .gitbashrc-user out of git without touching the tracked .gitignore
exclude_user_config() {
    local exclude
    exclude=$(git rev-parse --git-path info/exclude 2>/dev/null) || return 0
    mkdir -p "$(dirname "$exclude")"
    if [[ -f "$exclude" ]] && grep -qxF ".gitbashrc-user" "$exclude"; then
        return 0
    fi
    # Make sure we start on a new line
    if [[ -s "$exclude" && -n "$(tail -c 1 "$exclude")" ]]; then
        echo >> "$exclude"
    fi
    echo ".gitbashrc-user" >> "$exclude"
    print_info "Added .gitbashrc-user to $exclude"
}

# winget package id of a dependency
winget_id() {
    case "$1" in
        fzf) echo "junegunn.fzf" ;;
        git-delta) echo "dandavison.delta" ;;
        bat) echo "sharkdp.bat" ;;
    esac
}

# Report missing optional dependencies and offer to install them with
# Homebrew, or winget on Windows
check_dependencies() {
    local missing=() dep
    command -v fzf >/dev/null 2>&1 || missing+=("fzf")
    command -v delta >/dev/null 2>&1 || missing+=("git-delta")
    command -v bat >/dev/null 2>&1 || command -v batcat >/dev/null 2>&1 || missing+=("bat")

    echo
    if [[ ${#missing[@]} -eq 0 ]]; then
        if require_fzf; then
            print_success "All dependencies installed."
        fi
        return 0
    fi

    echo "Missing optional dependencies: ${missing[*]}"
    echo "  fzf (>= $GB_FZF_MIN_VERSION) - interactive menus, git-delta - diff highlighting, bat - file previews"
    local -a install
    local manager
    if gb_is_windows; then
        manager="winget"
        install=(winget install --exact --id)
    else
        manager="Homebrew"
        install=(brew install)
    fi
    if ! command -v "${install[0]}" >/dev/null 2>&1; then
        if gb_is_windows; then
            echo "Install them with a package manager, e.g.: scoop install ${missing[*]/git-delta/delta}"
        else
            echo "Install them with your package manager, e.g.: sudo apt install ${missing[*]}"
        fi
        return 0
    fi
    local package
    if gb_confirm "Install them with $manager?" y; then
        for dep in "${missing[@]}"; do
            package="$dep"
            gb_is_windows && package=$(winget_id "$dep")
            if "${install[@]}" "$package"; then
                print_success "$dep installed"
            else
                print_error "Failed to install $dep"
            fi
        done
        gb_is_windows && print_info "Open a new terminal to pick up the installed programs."
    fi
}

# Offer to add the shell integration to the rc file of the user's shell
# Line that loads the PowerShell functions, in $PROFILE
PWSH_INIT_LINE='gitbash --init --shell=pwsh | Out-String | Invoke-Expression'

# Offer to load the functions in the profiles of Windows PowerShell (powershell.exe)
# and PowerShell 7 (pwsh.exe), and to allow local scripts if needed.
# PowerShell edits its own profile: it may be UTF-16, which bash can't append to.
check_pwsh_integration() {
    local exe info profile has policy found=false
    # Prints "<profile>|<True if it loads gitbash>|<execution policy>" (no double
    # quotes in PowerShell commands: they don't survive the Windows command line)
    local query="\$p = \$PROFILE; \$has = (Test-Path -LiteralPath \$p) -and [bool](Select-String -Quiet -SimpleMatch -Pattern 'gitbash --init' -LiteralPath \$p); Write-Output (\$p + '|' + \$has + '|' + (Get-ExecutionPolicy))"
    for exe in powershell.exe pwsh.exe; do
        command -v "$exe" >/dev/null 2>&1 || continue
        info=$("$exe" -NoProfile -NonInteractive -Command "$query" 2>/dev/null | tr -d '\r' | tail -n 1)
        IFS='|' read -r profile has policy <<< "$info"
        [[ -n "$profile" ]] || continue
        found=true

        echo
        if [[ "$has" == "True" ]]; then
            print_info "PowerShell integration already configured in $profile"
        elif gb_confirm "Load the gitbash functions in PowerShell ($profile)?" y; then
            if "$exe" -NoProfile -NonInteractive -Command \
                "\$p = \$PROFILE; if (!(Test-Path -LiteralPath \$p)) { New-Item -Force -Path \$p | Out-Null }; Add-Content -LiteralPath \$p '$PWSH_INIT_LINE'"; then
                print_success "Added to $profile. Open a new PowerShell window to use it."
            else
                print_error "Could not change $profile. Add this line yourself: $PWSH_INIT_LINE"
            fi
        fi

        # Restricted (the default of Windows PowerShell) and AllSigned block the profile
        case "$policy" in
            Restricted|AllSigned|Undefined)
                # A security setting: never changed by pressing Enter or by GITBASH_ASSUME_YES
                if gb_confirm --strict "PowerShell blocks scripts, including your profile ($policy). Allow local scripts (execution policy RemoteSigned)?" n; then
                    if "$exe" -NoProfile -NonInteractive -Command 'Set-ExecutionPolicy -Scope CurrentUser RemoteSigned -Force'; then
                        print_success "Local scripts allowed."
                    else
                        print_error "Could not change the execution policy (it may be set by your organization)."
                    fi
                fi
                ;;
        esac
    done
    if [[ "$found" == false ]]; then
        echo
        print_info "For PowerShell, add this line to your \$PROFILE:"
        echo "  $PWSH_INIT_LINE"
    fi
}

check_shell_integration() {
    local shell_name shell_rc
    # Can't tell PowerShell from Git Bash here: offer both
    gb_is_windows && check_pwsh_integration
    shell_name=$(basename "${SHELL:-}")
    case "$shell_name" in
        zsh) shell_rc="$HOME/.zshrc" ;;
        bash)
            if [[ -f "$HOME/.bashrc" ]]; then
                shell_rc="$HOME/.bashrc"
            else
                shell_rc="$HOME/.bash_profile"
            fi
            ;;
        *)
            if ! gb_is_windows; then
                echo
                print_info "Shell '$shell_name' is not supported for integration. Use 'gitbash <command>' or aliases."
            fi
            return 0
            ;;
    esac

    echo
    if [[ -f "$shell_rc" ]] && grep -q 'gitbash --init' "$shell_rc"; then
        print_info "Shell integration already configured in $shell_rc"
        return 0
    fi
    if gb_confirm "Add 'eval \"\$(gitbash --init)\"' to $shell_rc?" y; then
        {
            echo
            echo '# gitbash shell integration'
            # shellcheck disable=SC2016  # written literally to the rc file
            echo 'eval "$(gitbash --init)"'
        } >> "$shell_rc"
        print_success "Added to $shell_rc. Restart your shell or run 'source $shell_rc'."
    fi
}

# =============================================================================
# Help and shell integration
# =============================================================================

# ASCII art logo with a color gradient, followed by the version.
# Plain text when stdout is not a terminal or NO_COLOR is set.
show_banner() {
    local -a art=(
        '        _ _   _               _     '
        '   __ _(_) |_| |__   __ _ ___| |__  '
        '  / _` | | __| '"'"'_ \ / _` / __| '"'"'_ \ '
        ' | (_| | | |_| |_) | (_| \__ \ | | |'
        '  \__, |_|\__|_.__/ \__,_|___/_| |_|'
        '  |___/                             '
    )
    local -a colors=(214 209 204 199 170 135)
    local i
    if _gb_color_ok 1; then
        for i in "${!art[@]}"; do
            printf '\033[1;38;5;%sm%s\033[0m\n' "${colors[$i]}" "${art[$i]}"
        done
        printf '  \033[1;38;5;135mv%s\033[0m \033[2m·\033[0m Interactive git utilities for bash\n' "$VERSION"
    else
        printf '%s\n' "${art[@]}"
        printf '  v%s - Interactive git utilities for bash\n' "$VERSION"
    fi
}

show_help() {
    show_banner
    echo
    gb_help << EOF
Usage:
    gitbash <command> [args...]
    gitbash --help | --version | --update
    gitbash --init [--prefix=PREFIX] [--shell=pwsh]
    gitbash --config | --config-local | --config-user

Commands:
  branch      Interactive menu for branch operations
  cleanstash  Delete stashes (multi-select)
  cleanup     Find and delete leftover local branches
  commit      Commit with optional push
  commits     List the branch's commits with revert option
  create      Create feature branch with Jira parsing
  pr          Open PR in browser
  repo        Open the repository in browser
  reset-repo  Reset the branch like a fresh clone
  stale       List stale remote branches
  stash       Create named stash
  stashes     Interactive stash menu
  status      Interactive staging with fzf
  switch      Switch branches with fzf
  unstash     Apply stash with fzf picker
  update      Merge latest main/master into current branch

Options:
  -h, --help       Show this help message
  -v, --version    Show version number
  --update         Update gitbash to the latest release
  --init           Print shell functions for calling commands directly
                   (--prefix=gb- creates gb-commit, gb-switch, ...;
                   --shell=pwsh prints PowerShell functions)
  --config         Configure gitbash and save to ~/.gitbashrc
  --config-local   Configure overrides for this repository (.gitbashrc, committed)
  --config-user    Configure personal overrides for this repository (.gitbashrc-user)

Examples:
  gitbash commit fix bug -p     # Commit and push
  gitbash switch feature        # Switch to branch containing "feature"
  gitbash create PROJ-123 fix   # Create feature/PROJ-123-fix

Shell Integration:
  Add to your .zshrc or .bashrc:
    eval "\$(gitbash --init)"
  PowerShell: see 'gitbash --init --shell=pwsh'

  This enables calling commands directly:
    commit fix bug -p
    switch feature

Dependencies (optional):
  fzf >= $GB_FZF_MIN_VERSION   Interactive menus (brew install fzf)
  git-delta       Better diffs (brew install git-delta)
  bat             Syntax highlighting (brew install bat)
EOF
}

# Print wrapper functions for the interactive shell. Commands still run in
# their own bash process, so nothing leaks into the user's shell.
show_init() {
    local prefix="" shell="sh" arg cmd bin_quoted
    for arg in "$@"; do
        case "$arg" in
            --prefix=*) prefix="${arg#--prefix=}" ;;
            --shell=bash|--shell=zsh|--shell=sh) shell="sh" ;;
            --shell=pwsh|--shell=powershell) shell="pwsh" ;;
            *) print_error "Unknown option for --init: $arg"; return 1 ;;
        esac
    done
    if ! [[ "$prefix" =~ ^[A-Za-z0-9_-]*$ ]]; then
        print_error "Invalid prefix '$prefix' (use letters, digits, '-' or '_')."
        return 1
    fi
    if [[ "$shell" == "pwsh" ]]; then
        show_init_pwsh "$prefix"
        return
    fi
    printf -v bin_quoted '%q' "$GITBASH_BIN"
    echo "# gitbash shell integration - add to your .zshrc or .bashrc:"
    echo "#   eval \"\$(gitbash --init${prefix:+ --prefix=$prefix})\""
    for cmd in "${COMMANDS[@]}"; do
        echo "${prefix}${cmd}() { $bin_quoted $cmd \"\$@\"; }"
    done
}

# Single-quoted PowerShell string
pwsh_quote() {
    local q="'"
    printf "'%s'" "${1//$q/$q$q}"
}

# The bash that PowerShell functions run gitbash with. On Windows, Git's
# bin\bash.exe: it puts git and the Unix tools on PATH, unlike usr\bin\bash.exe.
pwsh_bash() {
    local bash_path git_root
    bash_path=$(command -v bash)
    if gb_is_windows && command -v cygpath >/dev/null 2>&1; then
        git_root=$(cygpath -w /)
        git_root="${git_root%\\}"
        if [[ -f "$git_root\\bin\\bash.exe" ]]; then
            printf '%s\n' "$git_root\\bin\\bash.exe"
        else
            cygpath -w "$bash_path"
        fi
    else
        echo "$bash_path"
    fi
}

# Functions for PowerShell ($PROFILE), running gitbash with bash
show_init_pwsh() {
    local prefix="$1" bash_q bin_q cmd bin="$GITBASH_BIN"
    gb_is_windows && command -v cygpath >/dev/null 2>&1 && bin=$(cygpath -m "$bin")
    bash_q=$(pwsh_quote "$(pwsh_bash)")
    bin_q=$(pwsh_quote "$bin")
    echo "# gitbash shell integration for PowerShell - add to your \$PROFILE:"
    echo "#   gitbash --init --shell=pwsh${prefix:+ --prefix=$prefix} | Out-String | Invoke-Expression"
    echo "function gitbash { & $bash_q $bin_q @args }"
    for cmd in "${COMMANDS[@]}"; do
        # 'switch' is a PowerShell keyword: a function by that name can't be called
        if [[ -z "$prefix" && "$cmd" == "switch" ]]; then
            echo "# switch is a PowerShell keyword: use 'gitbash switch', or --prefix (e.g. gb-switch)"
            continue
        fi
        echo "function ${prefix}${cmd} { & $bash_q $bin_q $cmd @args }"
    done
}

# =============================================================================
# Main entry point
# =============================================================================

main() {
    case "${1:-}" in
        -h|--help|"")
            show_help
            ;;
        -v|--version)
            echo "gitbash $VERSION"
            ;;
        --update)
            gb_self_update
            ;;
        --init)
            shift
            show_init "$@"
            ;;
        --config)
            configure_wizard global
            ;;
        --config-local)
            configure_wizard local
            ;;
        --config-user)
            configure_wizard user
            ;;
        -*)
            print_error "Unknown option '$1'"
            echo "Run 'gitbash --help' for available options." >&2
            return 1
            ;;
        *)
            local cmd="$1"
            shift
            if ! is_command "$cmd"; then
                print_error "Unknown command '$cmd'"
                echo "Run 'gitbash --help' for available commands." >&2
                return 1
            fi
            gb_load_config
            gb_update_check "$cmd" "$@"
            # Commands run gitbash again (e.g. pr runs commit): no update prompt in there
            GITBASH_NESTED=1
            # shellcheck source=/dev/null
            source "$COMMANDS_DIR/$cmd.sh"
            "$cmd" "$@"
            ;;
    esac
}

main "$@"
exit $?
