# shellcheck shell=dash

___x_cmd_gh_repo_download(){
    param:scope ___x_cmd_github
    param:dsl <<A
options:
    #1              "<ownerPath>/<RepoPath> or <ownerPath>/<RepoPath>@<ref>"        <>
    #2              "output file path"                                              <>=""
A
    param:run

    local repo="$1"
    local ref=""
    case "$repo" in
        *@*)
            repo="${1%'@'*}"
            ref="${1##*'@'}"
            ;;
        *)
            local x_default_branch=""
            ___x_cmd_gh___get_x_default_branch_
            if [ -n "$x_default_branch" ]; then
                ref="$x_default_branch"
            else
                gh:error "Can not get default branch of repo $repo. Please have check it."
                return 1
            fi
            ;;
    esac
    ___x_cmd_gh_param_init_owner_repo
    [ -n "$owner_repo" ] || M='accepts 1 arg (<owner>/<repo>), received empty' arg:ret:64

    local ball_type="tarball"
    local gh_output_folder=""
    local gh_output="${2:-"./${owner_repo%/*}-${owner_repo##*/}-${ref}.tar.gz"}"

    case "$gh_output" in
        *.zip)
            ball_type="zipball"
            ;;
        *.tar.gz|*.tgz)
            ;;
        *)
            gh_output="$___X_CMD_GH_CACHE/repo/download/${owner_repo}/${ref}.tar.gz"
            gh_output_folder="$2"
            ;;
    esac

    if ! ___x_cmd_gh_curl download "/repos/${owner_repo}/${ball_type}/${ref}" "$gh_output"; then
        [ "$(___x_cmd_gh_resp_code)" != 404 ] || gh:warn "Possible the repository is empty or no exist. Please have check it."
        x rmrf "$gh_output"
        return 1
    fi
    if [ -n "$gh_output_folder" ]; then
        x mkdirp "$gh_output_folder"
        command tar xzvf "$gh_output" -C "$gh_output_folder" --strip-components=1 1>/dev/null 2>&1 || {
                gh:error "decompress archive file failure"
                x rmrf "$gh_output"
                return 1
            }
    fi
}
