<?php

function fusioncore_poll_hostgroupmembers(&$raw_data) {
    
    $hostgroup_members = array();
    $hostgrouplist = array();

    $xi = false;
    $core = false;

    // xi
    if (!empty($raw_data['hostgrouplist']['hostgroup'])) {
        $xi = true;
        $hostgrouplist = $raw_data['hostgrouplist']['hostgroup'];

        if ($raw_data['hostgrouplist']['recordcount'] == 1)
            $hostgrouplist = array($hostgrouplist);
    }

    // core
    if (!empty($raw_data['data']['hostgrouplist'])) {
        $core = true;
        $hostgrouplist = $raw_data['data']['hostgrouplist'];
    }

    // have to let the poller know we're not the one..
    if (!$xi && !$core)
        return null;

    foreach($hostgrouplist as $hostgroup) {

        $hostgroup_name = '';
        $hostgroup_alias = '';
        $members = array();

        if ($xi) {

            if (!empty($hostgroup['hostgroup_name']))
                $hostgroup_name = $hostgroup['hostgroup_name'];

            if (isset($hostgroup['members']['host'])) {

                // xi is a bit weird. if theres only one host, then there is no array..
                if (!empty($hostgroup['members']['host']['host_name'])) {

                    $members[] = $hostgroup['members']['host']['host_name'];

                } else {

                    if (isset($hostgroup['members']['host'])) {
                        foreach ($hostgroup['members']['host'] as $host) {

                            if (!empty($host['host_name'])) {

                                $members[] = $host['host_name'];
                            }
                        }
                    }
                }
            }
        }
        if ($core) {

            if (!empty($hostgroup['group_name']))
                $hostgroup_name = $hostgroup['group_name'];

            if (!empty($hostgroup['alias']))
                $hostgroup_alias = $hostgroup['alias'];

            if (isset($hostgroup['members']) && is_array($hostgroup['members'])) {
                foreach ($hostgroup['members'] as $index => $host) {
                    $members[] = $host;
                }
            }
        }

        if (empty($hostgroup_alias))
            $hostgroup_alias = $hostgroup_name;

        $hostgroup_members[$hostgroup_name] = array(
            'alias' => $hostgroup_alias,
            'members' => $members,
            );
    }

    return array('hostgroup_members' => $hostgroup_members);
}

