/*
    ssl.me - SSL Plugin. This is the interface above SSL providers.
 */

Me.load({
    blend: [
        '?est',
        'openssl.me',
    ],
    targets: {
        ssl: {
            configurable: true,
            description: 'Secure Socket Layer Interface',
            discovers: [ 'openssl', 'est' ],
            uses:      [ 'openssl', 'est' ],
            config: function (target) {
                let provider
                for each (p in target.discovers) {
                    let ptarget = me.targets[p]
                    if (ptarget.explicit) {
                        if (ptarget.enable) {
                            provider = p
                            break
                        } else if (ptarget.explicit != 'without') {
                            throw 'Required SSL provider "' + p + '" is not enabled'
                        }
                    }
                }
                for each (p in target.discovers) {
                    if (p == provider) {
                        continue
                    }
                    if (me.targets[p] && me.targets[p].enable && !provider) {
                        provider = p
                    } else if (provider) {
                        me.targets[p].enable = false
                        me.targets[p].diagnostic = 'Using the "' + provider + '" SSL provider instead.'
                    }
                }
                if (provider) {
                    let from = me.targets[provider]
                    target.provider = provider
                    for each (field in ['defines', 'includes', 'libraries', 'libpaths', 'imports']) {
                        if (from[field]) {
                            target[field] = from[field]
                        }
                    }
                    target.description += ' (' + me.targets[provider].description + ')'

                } else {
                    throw 'No enabled SSL providers'
                }
            },
            without: function(target) {
                for each (p in target.discovers) {
                    me.targets[p].enable = false
                    me.targets[p].diagnostic = 'configured --without ssl'
                }
            }
        }
    }
})
