# shellcheck shell=sh disable=SC3043

# author:       Li Junhao           l@x-cmd.com    edwinjhlee.github.io
# maintainer:   Li Junhao
x log init p7zd

if command -v 7z 1>/dev/null 2>&1; then
    _7zd_which(){
        command -v 7z
    }

else
_7zd_which(){
    local target="$___X_CMD_ROOT_DATA/.bin/7zd"
    ___x_cmd_cmds_mkdir -p "$target"
    xrc os
    local arch
    arch="$(___x_cmd os arch)"
    local osname
    osname="$(___x_cmd os name)"
    local release
    release="$(uname -r)"

    local exe
    case "$osname-$release" in
        win*)
            exe=7zd.win.x64.exe        
        ;;
        linux*|darwin*)     
            exe=7zd.${osname}.${arch}  
        ;;
        *)
            p7zd:error "Unsupported [arch=$arch] [os=$osname]!" >&2; 
            return 1 
        ;;
    esac
    p7zd:debug "Downloading: p7zip/main/bin/$exe"
    if CACHE="$target/$exe" ___x_cmd httpget gitx static-build "p7zip" main "7zd/19.00/$exe" "$target/$exe"; then
        chmod +x "$target/$exe" && printf "%s" "$target/$exe"
    else
        p7zd:error "Fail to download: p7zip/main/bin/$exe"
        return 1
    fi
}

fi

___x_cmd_p7zd(){
    local p7z_path
    p7z_path="$(_7zd_which)"
    eval "
        p7zd(){
            $p7z_path \${1:+\"\$@\"}
        }
    "
    p7zd ${1:+"$@"}
}

___x_cmd_p7za(){
    x pkg sphere xbin init 7za p7za || return
    p7za "$@"
}