# -*- shell-script -*-

bashrun_plugins_checked="$bashrun_cache_home/plugins-checked"

function §plugin.find {
    §xdg -e config "bashrun2/plugins/${1}.rc"
}

function §plugin.check {
    local file="$1"
    local name="$name"
    local retval=0
    declare -i i

    §syntax? $file
    retval=$?
    
    if ! §plugin.checked? "$file"; then
	printf '%s\n' "$name.rc" >> $bashrun_plugins_checked
    fi
    return $retval
}

function §plugin.checked? {
    grep "$1" "$bashrun_plugins_checked" &>/dev/null
}

function +plugins { 
    local file=""
    local name=""
    local errors=""
    local errorfile="$bashrun_cache_home/syntax-errors"
    for name in $*; do
	file="$(§plugin.find "$name")"
	if [[ -n "$file" ]]; then
	    if ! §plugin.checked? "$name"; then
		if ! §plugin.check "$file" "$name"; then
		    errors="$(<$errorfile)"
		    errors="${errors//$'\n'/\\n}"
		    §message "Warning" \
		    "Plugin \"$name\" contains syntax errors:

                         $errors

                         Skipping plugin \"$name\"..."
		else
		    §debug -v "$name" "->" -c "$(§tilde_path $file)"
		    source "$file"
		fi
		[[ -f "$errorfile" ]] && /bin/rm "$errorfile"
	    else
		if §plugin.check "$file" "$name"; then
		    §debug -v "$name" "->" -c "$(§tilde_path $file)"
		    source "$file"
		fi
	    fi
	else
	    if ! §plugin.checked? "^$name\\.rc"; then
		§message "Warning" \
		    "Plugin \"$name\" not found: no such file(s):

                     $(§tilde_path $bashrun_config_home/plugins)/$name.rc\n
                     $bashrun_config_dirs/plugins/$name.rc

                     Skipping plugin \"$name\"..."

	             printf '%s\n' "$name.rc" >> "$bashrun_plugins_checked"
	    fi
	fi
    done
}
