#!/usr/bin/env zsh

#
# For compatibility zplug v1
#

__logo() {
    cat <<'EOLOGO'
               _
     _____ __ | |_   _  __ _
    |_  / '_ \| | | | |/ _` |
     / /| |_) | | |_| | (_| |
    /___| .__/|_|\__,_|\__, |
        |_|            |___/
EOLOGO
}

__get_zplug() {
    local i
    local url="https://github.com/zplug/zplug"

    : ${ZPLUG_HOME:=$1}
    if [[ -z $ZPLUG_HOME ]]; then
        printf '[zplug] $ZPLUG_HOME is empty\n' >&2
        return 1
    fi

    if [[ -d $ZPLUG_HOME ]]; then
        printf "[zplug] zplug is already installed\n" >&2
        return 1
    fi

    if (( ! $+commands[git] )); then
        printf "[zplug] zplug requires git command\n" >&2
        return 1
    fi

    git clone \
        "$url" \
        "$ZPLUG_HOME" \
        &>/dev/null &

    while true
    do
        for i in ⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏
        do
            print -P -n " $i Downloading %Bzplug%b to $ZPLUG_HOME\r"
            sleep 0.02
        done
        if [[ -z ${${(v)jobstates##*:*:}%"="*} ]]; then
            break
        fi
    done

    printf "\r\033[0K"
    if [[ -d $ZPLUG_HOME ]]; then
        printf "[zplug] Welcome to the world of zplug...\U1F33A\n"
    else
        printf "[zplug] Oops! Failed to install...\n" >&2
        print -P -n "[zplug] For more details, see also %U$url%u\n" >&2
        return 1
    fi
}

function() {
    local init_file="${${(%):-%x}:A:h}/init.zsh"
    if [[ -z $ZSH_VERSION ]]; then
        printf "[zplug] zplug must be run on ZSH\n" >&2
        return 1 2>&- || exit 1
    fi

    # Check if current zsh is interactive
    if [[ $- =~ i ]]; then
        # source
        if [[ -f $init_file ]]; then
            source "$init_file"
            return $status
        else
            __logo >&2
            printf "[zplug] cannot find $init_file\n" >&2
            return 1
        fi
    else
        __get_zplug "$@"
        exit $status
    fi
} "$@"
