#!/bin/zsh
ginit() {
    git init;
    git add ${*:-"."};
    git commit -a -m "Initial Commit"
}

# define a function that calls different versioning systems depending on
# detected vcs for current directory
# usage: defvcsfun <command name> <parameters for git> <parameters for hg> <parameters for svn>
# see below for examples
defvcsfun() {
    local name=$1; shift
    local args=($@)
    eval "$name() {
        case \$VCS_DETECTED in
            git)
                git ${=args[1]} \"\$@\";;
            hg)
                hg ${=args[2]} \"\$@\";;
            svn)
                svn ${=args[3]} \"\$@\";;
            *)
                echo \"unknown vcs: \$VCS_DETECTED\";;
        esac
    }"
}

#VCS      command   git             hg              svn
defvcsfun gst       "status -s"         "status"        "status"
defvcsfun gpl       "pull --autostash"  "pull"          "update"
defvcsfun gcm       "commit"            "commit"        "commit"
defvcsfun ga        "add"               "add"           "add"
defvcsfun gpu       "push"              "push"          "i_am_not_distributed_please_dont_push_me"

alias gco="git checkout"
alias gca="git commit -a"
alias gap="git add --patch"


gls() {
    zmodload zsh/mapfile
    gitignore="$(git rev-parse --show-toplevel 2>/dev/null)/.gitignore"
    globalgitignore="$(git config core.excludesfile)"

    typeset -a ignores
    for i in $gitignore $globalgitignore; do
        if [[ -e $i ]]; then
            for ignore in "${(f)mapfile[$i]}"; do
                ignores+="--ignore=$ignore"
            done
        fi
    done

    ls --color=auto -h $ignores "$@"
}

alias gll="gls -l"
alias glll="gls -la"

gclone() {
    local oldurl
    local url
    if [[ -n $1 ]]; then
        url=$1
    else
        echo "${fg_bold[green]}Getting url from cliboard:"
        url=$(xclip -o -selection clipboard)
        echo $url
    fi

    shift
    local git_hosts=(
        gitlab2.informatik.uni-wuerzburg.de
        github.com
    )

    for host in $git_hosts; do
        if [[ "$url" =~ "^https://$host" ]]; then
            oldurl=$url
            url=$(echo ${url//https:\/\/$host\//git@$host:} | grep -oe '^[^/]*/[^/]*')
        fi
    done

    if [[ -n "$oldurl" ]]; then
        echo "Correcting url to $url"
    fi

    git clone $url "$@"
}