﻿# encoding: utf-8
# api: clicky
# type: init
# version: 0.2
# title: Add plain scripts
# description: Loads undocumented scripts from given directory into Clicky menu
# category: ui
# state: beta
# config:
#   { name: plain_scripts_dir, type: str, description: path to scan for undocumented PS scripts }
#   { name: plain_scripts_type, type: select, select: cli|window|inline, description: how to run non-PMD scripts }
# hidden: 1
# nomenu: 1
#
# Scans a given directory for plain powershell scripts. If no PMD is
# found embeds them into the menu with dummy values.
#
# This is used to craft a list of filename-only menu entries from
# undocumented tools.
#

# default config
@{
    plain_scripts_dir = "./powershell/scripts/*.ps1" # dirs to scan
    plain_scripts_type = "cli"            # could be inline
    plain_scripts_menu = "PlainScripts"   # menu name
}.GetEnumerator() | % {
    if (-not $cfg.containsKey($_.Key)) { $cfg[$_.Key] = $_.Value }
}


# menuitem moving (at this point the new menu was already added in 'Extras', so just move it to main menu bar)
if ($GUI -and $GUI.w) {
    if ($Menu_CAT = $GUI.w.findName("Menu_"+$cfg.plain_scripts_menu.toUpper()) ) {
        $Menu_MAIN = $GUI.w.findName("Menu_CMD").Parent
        $Menu_CAT.Parent.Items.Remove($Menu_CAT)
        $Menu_CAT.Header = $cfg.plain_scripts_menu
        $Menu_MAIN.Items.Insert(3, $Menu_CAT)
    }
    return
}
# reregister as init-gui (this plugin originally runs as `init`, but then should be invoked a second time in `init-gui` stage)
else {
    $_.type = "init-gui"   # simply adapt existing entry in $menu[]
}


# scan files, add to $menu list
$menu += @(Get-Item $cfg.plain_scripts_dir) | % {

    if (Is-PluginCompatible ($meta = Extract-PluginMeta $_)) {
        # pass
    }
    else {
        # stub fields
        $meta = @{
            fn = $_.FullName
            id = $_.BaseName
            api = "powershell" 
            type = ($cfg.plain_scripts_type)
            category= ($cfg.plain_scripts_menu.toLower())
            version = "0.0"
            title = $_.Name
            description = "plain powershell script"
            doc = "No documentation"
            author = "unknown"
            state = "unknown"
            menu = 1
            icon = "cmd"
            config = @()
            vars = @()
        }
        # try to gather something from DocBlock
        if ($help = Get-Help $_.FullName) {
            if ($help.NOTES) { $meta.doc = $help.NOTES }
            if ($help.DESCRIPTION) { $meta.description = $help.DESCRIPTION }
            if ($help.VERSION) { $meta.version = $help.VERSION }
        }
    }

    ($meta)
}
