#!/usr/bin/env zsh
#
# Copyright (c) 2016-2021 Sebastian Gniazdowski and contributors
# Copyright (c) 2021-2022 zdharma-continuum and contributors
#

builtin emulate -L zsh
setopt extendedglob warncreateglobal typesetsilent

[[ -z $ICE[submods] ]] && return 0

[[ "$1" = plugin ]] \
    && local type="$1" user="$2" plugin="$3" id_as="$4" dir="$5" \
    || local type="$1" url="$2" id_as="$3" dir="$4"

local -a mods parts lines
local mod
mods=(${(@s.;.)ICE[submods]})

for mod in "${mods[@]}"; do
    parts=("${(@s:->:)mod}")
    parts=("${parts[@]//((#s)[[:space:]]##|[[:space:]]##(#e))/}")

    +zi-log "{m} {b}submods annex{rst}: Updating submodule $parts[1] (path: $parts[2])"

    if [[ "${parts[1]}" != (http|https|ftp|ftps|scp)://* ]]; then
        parts[1]="https://github.com/${parts[1]}"
    fi

    command git -C "$dir/${parts[2]}" fetch

    lines=(${(f)"$(command git -C "$dir/${parts[2]}" log --color --date=short --pretty=format:'%Cgreen%cd %h %Creset%s %Cred%d%Creset%n' ..FETCH_HEAD)"})
    lines=("${(S)lines[@]//\(([,[:blank:]]#(origin|HEAD|master)[^a-zA-Z]##(HEAD|origin|master)[,[:blank:]]#)#\)/}")

    (( $#lines )) && print -rl -- "${lines[@]}"

    command git -C "${dir}/${parts[2]}" pull --no-stat ${=ICE[pullopts]:---ff-only} origin 2>&1 | {
        command egrep -v '(FETCH_HEAD|up to date\.|From.*://)' || :
    }

done

# vim: set expandtab filetype=zsh shiftwidth=4 softtabstop=4 tabstop=4:
