function guifi_kamikaze_files($dev, $zone)
{
    //SOME VARIABLES
    $dns = guifi_get_dns($zone, 2);
    $lan = guifi_unsolclic_if($dev->id, 'wLan/Lan');
    $lan_network = _ipcalc($lan->ipv4, $lan->netmask);
    switch ($dev->variable['model_id']) {
        case "38":
            // RouterStation
            $wireless_model = 'atheros';
            $lan_iface = 'eth0';
            $lan2_iface = 'eth1';
            $packages = 'ar71xx/packages';
            break;
        default:
            _outln_comment('model id not supported');
            exit;
    }
    // SECTION FILES
    _outln_comment();
    _outln_comment();
    _outln_comment(t('Wireless Settings'));
    print '<pre>';
    function wds_add($dev, $radio, $radio_id)
    {
        $wds_links = array();
        foreach ($radio[interfaces] as $interface_id => $interface) {
            if ($interface[interface_type] == 'wds/p2p') {
                foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                    foreach ($ipv4[links] as $link_id => $link) {
                        if ($link['link_type'] == 'wds') {
                            $wds_links[] = $link;
                        }
                    }
                }
                $ifcount = 0;
                foreach ($wds_links as $key => $wds) {
                    if (preg_match("/(Working|Testing|Building)/", $wds['flag'])) {
                        $status = 'active';
                        print 'uci set wireless.@wifi-iface[' . $radio_id . '].bssid' . $ifcount . '=' . $wds['interface']['mac'] . '<br />';
                        $ifcount++;
                    } else {
                        $status = 'disabled';
                        print '# uci set wireless.@wifi-iface[' . $radio_id . '].bssidX=' . $wds['interface']['mac'] . ' # ' . t($wds['flag']) . '<br />';
                    }
                }
            }
        }
    }
    function wds_network($dev, $radio)
    {
        $ifcount = '0';
        foreach ($radio[interfaces] as $interface_id => $interface) {
            foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                foreach ($ipv4[links] as $link_id => $link) {
                    if ($link['link_type'] == 'wds') {
                        $wds_links = array();
                        $wds_links[] = $link;
                        foreach ($wds_links as $key => $wds) {
                            $hostname = guifi_get_hostname($wds['device_id']);
                            if (preg_match("/(Working|Testing|Building)/", $wds['flag'])) {
                                $status = 'active';
                                print '
## wds_' . $hostname . '
uci delete network.wds_' . $hostname . '
uci set network.wds_' . $hostname . '=interface
uci set network.wds_' . $hostname . '.ifname=ath' . $radio[radiodev_counter] . '.wds' . $ifcount . '
uci set network.wds_' . $hostname . '.proto=static
';
                                $ifcount++;
                            } else {
                                $status = 'disabled';
                                print '
##### ' . t($wds['flag']) . ' ####
## wds_' . $hostname . '
# uci set network.wds_' . $hostname . '.ifname=ath' . $radio[radiodev_counter] . '.wdsX
# uci set network.wds_' . $hostname . '.proto=none
';
                            }
                        }
                        if ($status == 'active') {
                            print 'uci set network.wds_' . $hostname . '.ipaddr=' . $ipv4[ipv4] . '
uci set network.wds_' . $hostname . '.netmask=' . $ipv4['netmask'] . '
';
                        } else {
                            print '# uci set network.wds_' . $hostname . '.ipaddr=' . $ipv4[ipv4] . '
# uci set network.wds_' . $hostname . '.netmask=' . $ipv4['netmask'] . '
';
                        }
                    }
                }
            }
        }
    }
    if (isset($dev->radios)) {
        foreach ($dev->radios as $radio_id => $radio) {
            $mode = 'apwds';
            $ssid = $radio[ssid];
            $channel = atheros_channel($radio);
            if ($channel <= 14) {
                $band = '11b';
            } else {
                $band = '11a';
            }
            if (empty($radio[antenna_mode])) {
                $radio[antenna_mode] = '1';
            } else {
                if ($radio[antenna_mode] != 'Main') {
                    $radio[antenna_mode] = '2';
                } else {
                    $radio[antenna_mode] = '1';
                }
            }
            if ($radio_id == '0') {
                $wireless_iface = 'wifi0';
                $network = 'wlanLan';
            } else {
                $wireless_iface = 'wifi' . $radio_id;
                $network = 'wlan' . ($radio_id + 1);
            }
            $wireless_model = 'atheros';
            $txant = $radio[antenna_mode];
            $rxant = $radio[antenna_mode];
            print '
## Radio: ' . $radio[ssid] . '
uci delete wireless.' . $wireless_iface . '
uci set wireless.' . $wireless_iface . '=wifi-device
uci set wireless.' . $wireless_iface . '.type=' . $wireless_model . '
uci set wireless.' . $wireless_iface . '.channel=' . $channel . '
uci set wireless.' . $wireless_iface . '.disabled=0
uci set wireless.' . $wireless_iface . '.hwmode=' . $band . '
uci set wireless.' . $wireless_iface . '.diversity=0
uci set wireless.' . $wireless_iface . '.txantenna=' . $txant . '
uci set wireless.' . $wireless_iface . '.rxantenna=' . $rxant . '
uci set wireless.' . $wireless_iface . '.txpower=16
uci set wireless.' . $wireless_iface . '.regdomain=31
uci set wireless.' . $wireless_iface . '.country=724
uci set wireless.' . $wireless_iface . '.distance=2000
uci delete wireless.@wifi-iface[' . $radio_id . ']
uci add wireless wifi-iface
uci set wireless.@wifi-iface[' . $radio_id . ']=wifi-iface
uci set wireless.@wifi-iface[' . $radio_id . '].device=' . $wireless_iface . '
uci set wireless.@wifi-iface[' . $radio_id . '].network=' . $network . '
uci set wireless.@wifi-iface[' . $radio_id . '].mode=' . $mode . '
uci set wireless.@wifi-iface[' . $radio_id . '].ssid=guifi.net-' . $radio[ssid] . '
uci set wireless.@wifi-iface[' . $radio_id . '].encryption=none
';
            wds_add($dev, $radio, $radio_id);
        }
    }
    print 'sleep 1</pre>';
    _outln_comment();
    _outln_comment();
    _outln_comment(t('Network Settings'));
    print '<pre>';
    function cable_network($dev)
    {
        foreach ($dev->interfaces as $interface_id => $interface) {
            switch ($interface[interface_type]) {
                case 'vlan1':
                    $iname = 'eth0:1';
                    break;
                case 'vlan2':
                    $iname = 'eth1';
                    break;
                case 'vlan3':
                    $iname = 'eth1:1';
                    break;
                default:
                    $iname = $interface[interface_type];
                    break;
            }
            foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                foreach ($ipv4[links] as $link_id => $link) {
                    $network = guifi_get_hostname($link[device_id]);
                    if (preg_match("/(Working|Testing|Building)/", $link['flag'])) {
                        $status = 'active';
                        if ($interface[interface_type] != 'wLan/Lan') {
                            print '
## cable_' . $network . '
uci delete network.' . $network . '
uci set network.' . $network . '=interface
uci set network.' . $network . '.ifname=' . $iname . '
uci set network.' . $network . '.proto=static
uci set network.' . $network . '.ipaddr=' . $ipv4[ipv4] . '
uci set network.' . $network . '.netmask=' . $ipv4[netmask] . '
';
                        }
                    } else {
                        $status = 'disabled';
                        print '
##### ' . t($link['flag']) . ' ####
## cable_' . $network . '
# uci set network.' . $network . '=interface
# uci set network.' . $network . '.ifname=' . $iname . '
# uci set network.' . $network . '.proto=static
# uci set network.' . $network . '.ipaddr=' . $ipv4[ipv4] . '
# uci set network.' . $network . '.netmask=' . $ipv4[netmask] . '
';
                    }
                }
            }
        }
    }
    print '
uci set network.loopback=interface
uci set network.loopback.ifname=lo
uci set network.loopback.proto=static
uci set network.loopback.ipaddr=127.0.0.1
uci set network.loopback.netmask=255.0.0.0

uci delete network.lan
uci delete network.wan
';
    if (isset($dev->radios)) {
        foreach ($dev->radios as $radio_id => $radio) {
            if (isset($radio[interfaces])) {
                foreach ($radio[interfaces] as $interface_id => $interface) {
                    if ($interface[interface_type] != 'wds/p2p') {
                        if (isset($interface[ipv4])) {
                            foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                                if ($interface[interface_type] == 'wLan/Lan') {
                                    $iface = '"ath0 eth0"';
                                    $network = 'wlanLan';
                                } else {
                                    $iface = 'wifi' . $radio_id;
                                    $network = 'wlan' . ($radio_id + 1);
                                }
                                $item = _ipcalc($ipv4[ipv4], $ipv4[netmask]);
                                // FILE NETWORK
                                print '
uci delete network.' . $network . '
uci set network.' . $network . '=interface
';
                                if ($interface[interface_type] == 'wLan/Lan') {
                                    print 'uci set network.' . $network . '.type=bridge
';
                                }
                                print 'uci set network.' . $network . '.ifname=' . $iface . '
uci set network.' . $network . '.proto=static
uci set network.' . $network . '.ipaddr=' . $ipv4[ipv4] . '
uci set network.' . $network . '.netmask=' . $ipv4[netmask] . '
uci set network.' . $network . '.dns="' . $dns . '"
';
                            }
                        }
                    }
                }
            }
            wds_network($dev, $radio);
        }
    }
    cable_network($dev);
    print 'sleep 1</pre>';
    //FILE FIREWALL
    _outln_comment();
    _outln_comment();
    _outln_comment(t('Firewall Settings'));
    print '<pre>';
    print 'uci set firewall.@defaults[0]=defaults
uci set firewall.@defaults[0].syn_flood=1
uci set firewall.@defaults[0].input=ACCEPT
uci set firewall.@defaults[0].output=ACCEPT
uci set firewall.@defaults[0].forward=ACCEPT
';
    print 'COUNTER=0
while [  $COUNTER -lt 64 ]; do
  uci delete firewall.@zone[0] > /dev/null 2>&1
  let COUNTER=COUNTER+1 
done
uci delete firewall.@forwarding[0]
';
    $icount = '0';
    foreach ($dev->radios as $radio_id => $radio) {
        foreach ($radio[interfaces] as $interface_id => $interface) {
            if ($interface[interface_type] == 'wLan' || $interface[interface_type] == 'wLan/Lan') {
                foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                    if ($interface[interface_type] == 'wLan/Lan') {
                        $network = 'wlanLan';
                    } else {
                        $network = 'wlan' . ($radio_id + 1);
                    }
                    print 'uci add firewall zone
uci set firewall.@zone[' . $icount . ']=zone
uci set firewall.@zone[' . $icount . '].name=' . $network . '
uci set firewall.@zone[' . $icount . '].input=ACCEPT
uci set firewall.@zone[' . $icount . '].output=ACCEPT
uci set firewall.@zone[' . $icount . '].forward=ACCEPT
';
                    $icount++;
                }
            }
        }
    }
    foreach ($dev->radios as $radio_id => $radio) {
        foreach ($radio[interfaces] as $interface_id => $interface) {
            if ($interface[interface_type] == 'wds/p2p') {
                foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                    foreach ($ipv4[links] as $link_id => $link) {
                        if ($link['link_type'] == 'wds') {
                            $wds_links = array();
                            $wds_links[] = $link;
                            foreach ($wds_links as $key => $wds) {
                                $hostname = guifi_get_hostname($wds['device_id']);
                                if (preg_match("/(Working|Testing|Building)/", $wds['flag'])) {
                                    print 'uci add firewall zone
uci set firewall.@zone[' . $icount . ']=zone
uci set firewall.@zone[' . $icount . '].name=wds_' . $hostname . '
uci set firewall.@zone[' . $icount . '].input=ACCEPT
uci set firewall.@zone[' . $icount . '].output=ACCEPT
uci set firewall.@zone[' . $icount . '].forward=ACCEPT
';
                                    $icount++;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    foreach ($dev->interfaces as $interface_id => $interface) {
        foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
            foreach ($ipv4[links] as $link_id => $link) {
                $hostname = guifi_get_hostname($link['device_id']);
                if (preg_match("/(Working|Testing|Building)/", $link['flag'])) {
                    print 'uci add firewall zone
uci set firewall.@zone[' . $icount . ']=zone
uci set firewall.@zone[' . $icount . '].name=' . $hostname . '
uci set firewall.@zone[' . $icount . '].input=ACCEPT
uci set firewall.@zone[' . $icount . '].output=ACCEPT
uci set firewall.@zone[' . $icount . '].forward=ACCEPT
';
                    $icount++;
                }
            }
        }
    }
    print 'sleep 1</pre>';
    _outln_comment();
    _outln_comment();
    _outln_comment(t('DHCP Static Leases'));
    print '<pre>';
    $dhcp_statics = array();
    $max = explode(".", $dev->ipv4);
    function merge_static($link, &$dhcp_statics, &$max, &$curr)
    {
        if (empty($link['interface'][mac])) {
            $link['interface'][mac] = 'FF:FF:FF:FF:FF:FF';
        }
        $dhcp_statics[] = array($link['interface'][ipv4][ipv4], $link['interface'][mac], guifi_get_hostname($link['interface'][device_id]));
        $curr = explode(".", $link['interface'][ipv4][ipv4]);
        if ($curr[3] > $max[3]) {
            $max[3] = $curr[3];
        }
    }
    $main_ip = guifi_main_ip($dev->id);
    $item = _ipcalc_by_netbits($main_ip[ipv4], $main_ip[maskbits]);
    $max = explode(".", $main_ip[ipv4]);
    // cable links
    foreach ($dev->interfaces as $interface) {
        foreach ($interface[ipv4] as $ipv4) {
            foreach ($ipv4[links] as $link) {
                if ($link['interface'][ipv4][ipv4] != '') {
                    $item2 = _ipcalc($link['interface'][ipv4][ipv4], $link['interface'][ipv4][netmask]);
                    if ($item[netid] == $item2[netid]) {
                        merge_static($link, $dhcp_statics, $max, $cur);
                    }
                }
            }
        }
    }
    // ap/client links
    foreach ($dev->radios as $radio) {
        foreach ($radio[interfaces] as $interface) {
            foreach ($interface[ipv4] as $ipv4) {
                foreach ($ipv4[links] as $link) {
                    if ($link['link_type'] == 'ap/client' and !empty($link['interface'][ipv4][ipv4])) {
                        merge_static($link, $dhcp_statics, $max, $cur);
                    }
                }
            }
        }
    }
    $statics = count($dhcp_statics) - 1;
    $totalstatics = count($dhcp_statics);
    $first = explode(".", $item[netid]);
    $last = explode(".", $item[broadcast]);
    $limit = $last[3] - 1 - ($first[3] + 3) - $totalstatics;
    $counter = '0';
    print 'COUNTER=0
while [  $COUNTER -lt 64 ]; do
  uci delete luci_ethers.@static_lease[0] > /dev/null 2>&1
  let COUNTER=COUNTER+1 
done
';
    foreach ($dhcp_statics as $static) {
        print '
## Device: ' . $static[2] . '
uci add luci_ethers static_lease
uci set luci_ethers.@static_lease[' . $counter . ']=static_lease
uci set luci_ethers.@static_lease[' . $counter . '].macaddr=' . $static[1] . '
uci set luci_ethers.@static_lease[' . $counter . '].ipaddr=' . $static[0] . '
';
        $counter++;
    }
    print 'sleep 1</pre>';
    // FILE DHCP
    _outln_comment();
    _outln_comment();
    _outln_comment(t('DHCP Settings'));
    print '<pre>';
    print 'uci set dhcp.@dnsmasq[0]=dnsmasq                                                                                                               
uci set dhcp.@dnsmasq[0].domainneeded=1
uci set dhcp.@dnsmasq[0].boguspriv=1
uci set dhcp.@dnsmasq[0].filterwin2k=0
uci set dhcp.@dnsmasq[0].localise_queries=1
uci set dhcp.@dnsmasq[0].local=/lan/
uci set dhcp.@dnsmasq[0].domain=lan
uci set dhcp.@dnsmasq[0].expandhosts=1
uci set dhcp.@dnsmasq[0].nonegcache=0
uci set dhcp.@dnsmasq[0].authoritative=1
uci set dhcp.@dnsmasq[0].readethers=1
uci set dhcp.@dnsmasq[0].leasefile=/tmp/dhcp.leases
uci set dhcp.@dnsmasq[0].resolvfile=/tmp/resolv.conf.auto
';
    foreach ($dev->radios as $radio_id => $radio) {
        foreach ($radio[interfaces] as $interface_id => $interface) {
            if ($interface[interface_type] == 'wLan' || $interface[interface_type] == 'wLan/Lan') {
                foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                    if ($interface[interface_type] == 'wLan/Lan') {
                        $iface = 'wlanLan';
                        $network = 'wlanLan';
                    } else {
                        $network = 'wlan' . ($radio_id + 1);
                    }
                    $max = explode(".", $ipv4[ipv4]);
                    foreach ($ipv4[links] as $link) {
                        if ($link['link_type'] == 'ap/client' and !empty($link['interface'][ipv4][ipv4])) {
                            $totalstaticss = count($ipv4[links]);
                        }
                    }
                    $first = explode(".", $item[netid]);
                    $last = explode(".", $item[broadcast]);
                    $limit = $last[3] - 1 - ($first[3] + 3) - $totalstaticss;
                    $totalstaticss = '0';
                    print '
uci delete dhcp.lan
uci delete dhcp.wan
uci set dhcp.' . $network . '=dhcp
uci set dhcp.' . $network . '.interface=' . $network . '
uci set dhcp.' . $network . '.leasetime=12h
uci set dhcp.' . $network . '.start=' . ($max[3] + 2) . '
uci set dhcp.' . $network . '.limit=' . $limit . '
uci set dhcp.' . $network . '.netmask=' . $ipv4[netmask] . '
';
                }
            }
        }
    }
    print 'sleep 1</pre>';
    $wds_links = array();
    foreach ($dev->radios as $radio_id => $radio) {
        foreach ($radio[interfaces] as $interface_id => $interface) {
            if ($interface[interface_type] == 'wds/p2p') {
                foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                    foreach ($ipv4[links] as $link_id => $link) {
                        if ($link['link_type'] == 'wds') {
                            $wds_links[] = $link;
                        }
                    }
                }
            }
        }
    }
    foreach ($wds_links as $key => $wds) {
        if ($wds['routing'] == 'BGP') {
            $wds_bgpd = '1';
        }
        if ($wds['routing'] == 'OSPF') {
            $wds_ospfd = '1';
        }
    }
    $cable_links = array();
    foreach ($dev->interfaces as $interface_id => $interface) {
        foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
            foreach ($ipv4[links] as $link_id => $link) {
                if ($link['link_type'] == 'cable') {
                    $cable_links[] = $link;
                }
            }
        }
    }
    foreach ($cable_links as $key => $cable) {
        if ($cable['routing'] == 'BGP') {
            $cable_bgpd = '1';
        }
        if ($cable['routing'] == 'OSPF') {
            $cable_ospfd = '1';
        }
    }
    // QUAGGA CONFIG FILES
    $file_zebra = '';
    _outln_comment();
    _outln_comment();
    _outln_comment(t('File /etc/quagga/zebra.conf'));
    print '<pre>';
    print 'true > /etc/quagga/zebra.conf';
    print '</pre>';
    // FILE OSPFD
    if ($wds_ospfd == '1' || $cable_ospfd == '1') {
        _outln_comment();
        _outln_comment();
        _outln_comment(t('File /etc/quagga/ospfd.conf'));
        print '<pre>';
        print 'cat > /etc/quagga/ospfd.conf << EOF
!
interface br-lan
!
router ospf
 ospf router-id ' . $lan->ipv4 . '
 redistribute bgp
';
        foreach ($dev->radios as $radio_id => $radio) {
            foreach ($radio[interfaces] as $interface_id => $interface) {
                if ($interface[interface_type] == 'wLan' || $interface[interface_type] == 'wLan/Lan') {
                    foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                        $network = _ipcalc($ipv4[ipv4], $ipv4[netmask]);
                    }
                    if (preg_match("/(Working|Testing|Building)/", $link['flag'])) {
                        print ' network ' . $network[netid] . '/' . $network[maskbits] . ' area 0<br />';
                    }
                }
            }
        }
        foreach ($wds_links as $key => $wds) {
            $iplocal[] = $wds['interface']['ipv4'];
            if ($wds['routing'] == 'OSPF') {
                $wds_network = _ipcalc($iplocal[$key][ipv4], $iplocal[$key][netmask]);
                if (preg_match("/(Working|Testing|Building)/", $wds['flag'])) {
                    print ' network ' . $wds_network[netid] . '/' . $wds_network[maskbits] . ' area 0<br />';
                }
            }
        }
        foreach ($dev->interfaces as $interface_id => $interface) {
            foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                foreach ($ipv4[links] as $link_id => $link) {
                    $item = _ipcalc($ipv4[ipv4], $ipv4[netmask]);
                    if ($link['routing'] == 'OSPF') {
                        if (preg_match("/(Working|Testing|Building)/", $link['flag'])) {
                            print ' network ' . $item[netid] . '/' . $item[maskbits] . ' area 0<br />';
                        }
                    }
                }
            }
        }
        print 'default-information originate
!
EOF

';
        print 'sleep 1</pre>';
    }
    // FILE BGPD
    if ($wds_bgpd == '1' || $cable_bgpd == '1') {
        _outln_comment();
        _outln_comment();
        _outln_comment(t('File /etc/quagga/bgpd.conf'));
        print '<pre>';
        print 'cat > /etc/quagga/bgpd.conf << EOF
!
interface br-lan
!
router bgp ' . $dev->id . '
bgp router-id ' . $lan->ipv4 . '
';
        foreach ($dev->radios as $radio_id => $radio) {
            foreach ($radio[interfaces] as $interface_id => $interface) {
                if ($interface[interface_type] == 'wLan' || $interface[interface_type] == 'wLan/Lan') {
                    foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                        $network = _ipcalc($ipv4[ipv4], $ipv4[netmask]);
                    }
                    print ' network ' . $network[netid] . '/' . $network[maskbits] . '<br />';
                }
            }
        }
        print 'redistribute ospf
';
        foreach ($wds_links as $key => $wds) {
            $iplocal[] = $wds['interface']['ipv4'];
            if ($wds['routing'] == 'BGP') {
                $wds_network = _ipcalc($iplocal[$key][ipv4], $iplocal[$key][netmask]);
                if (preg_match("/(Working|Testing|Building)/", $wds['flag'])) {
                    print ' network ' . $wds_network[netid] . '/' . $wds_network[maskbits] . '<br />';
                }
            }
        }
        foreach ($dev->interfaces as $interface_id => $interface) {
            foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                foreach ($ipv4[links] as $link_id => $link) {
                    $item = _ipcalc($ipv4[ipv4], $ipv4[netmask]);
                    if ($link['routing'] == 'BGP') {
                        if (preg_match("/(Working|Testing|Building)/", $link['flag'])) {
                            print ' network ' . $item[netid] . '/' . $item[maskbits] . '<br />';
                        }
                    }
                }
            }
        }
        foreach ($dev->radios as $radio_id => $radio) {
            foreach ($radio[interfaces] as $interface_id => $interface) {
                foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                    foreach ($ipv4[links] as $link_id => $link) {
                        if ($link['routing'] == 'BGP') {
                            if (preg_match("/(Working|Testing|Building)/", $link['flag'])) {
                                print ' neighbor ' . $link['interface']['ipv4']['ipv4'] . ' remote-as ' . $link['device_id'] . '
';
                            }
                        }
                    }
                }
            }
        }
        foreach ($dev->interfaces as $interface_id => $interface) {
            foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                foreach ($ipv4[links] as $link_id => $link) {
                    if ($link['routing'] == 'BGP') {
                        if (preg_match("/(Working|Testing|Building)/", $link['flag'])) {
                            print ' neighbor ' . $link['interface']['ipv4']['ipv4'] . ' remote-as ' . $link['device_id'] . '
';
                        }
                    }
                }
            }
        }
        print 'EOF

';
        print 'sleep 1</pre>';
    }
    //FILE OPKG
    $opkg_conf = '
src/gz snapshots http://downloads.openwrt.org/snapshots/' . $packages . '
dest root /
dest ram /tmp
lists_dir ext /var/opkg-lists
option overlay_root /jffs
';
    _outln_comment();
    _outln_comment();
    _outln_comment(t('File /etc/opkg.conf'));
    openwrt_out_file($opkg_conf, '/etc/opkg.conf');
}
function guifi_ipcalc_find_subnet($base_ip, $mask_range, $mask_allocated, $ips_allocated = NULL)
{
    // if current allocated addresses are not given,take it from the database
    if (empty($ips_allocated)) {
        $ips_allocated = guifi_ipcalc_get_ips($base_ip, $mask_range);
    }
    // print "Looking sizeof $mask_allocated at $base_ip / $mask_range into ".count($ips_allocated)." keys\n<br />";
    // start looking at the given base ip to look at up to the size of mask_range
    // in chunks of "increments"
    $net_dec = is_numeric($base_ip) ? $base_ip : ip2long($base_ip);
    $item = _ipcalc($base_ip, $mask_range);
    $end_dec = ip2long($item['broadcast']);
    if ($mask_allocated == '255.255.255.255') {
        $increment = 1;
    } else {
        $item = _ipcalc($base_ip, $mask_allocated);
        $increment = $item['hosts'] + 2;
    }
    if ($end_dec < $net_dec + $increment) {
        // space to look for is greater than the range to look at, no need to search
        return FALSE;
    }
    while ($net_dec <= $end_dec) {
        // check that we are starting from a network base address, if not,
        // advance to the end of the current subnetwork to find at the next,
        // forcing $net_dec to be a valid base address
        $item = _ipcalc(long2ip($net_dec), $mask_allocated);
        if (ip2long($item['netid']) != $net_dec) {
            $net_dec = ip2long($item['broadcast']) + 1;
        }
        $last = $net_dec + $increment;
        $key = $net_dec;
        // is there any ip allocated in the range between net_dec and increment?
        // print "Going to find between ".long2ip($net_dec)." and ".long2ip($last)." \n<br />";
        while ($key < $last) {
            if (isset($ips_allocated[$key])) {
                break;
            } else {
                $key++;
            }
        }
        // if no ips found (reached end of range), return succesfully
        if ($key == $last) {
            //      print "IPs allocated: ".$ips_allocated[$net_dec+1]."\n";
            if ($ips_allocated[$net_dec + 1] == 32 or !isset($ips_allocated[$net_dec + 1])) {
                return long2ip($net_dec);
            }
        }
        // space was already used
        // now advance the pointer up to the end of the network of the current
        // address found
        $item = _ipcalc_by_netbits(long2ip($key), $ips_allocated[$key]);
        $net_dec = ip2long($item['broadcast']) + 1;
    }
    // end while
    // no space available
    return FALSE;
}
function ospf_net($cnmlid)
{
    $nmax = 200;
    //num maxim de nodes a procesar
    $networks = array();
    //array de subxarxes de la zona
    $nodes = array();
    //array de nodes id de la zona
    $nodesid = array();
    //array de dades del node + control de repeticions
    $subnets = array();
    //array de subxarxes agrupades
    $azones = array();
    //array de zones implicades
    $aznets = array();
    //array de xarxes de les zones implicades
    $nreg = 0;
    $n = 0;
    $CNML = new SimpleXMLElement('<cnml></cnml>');
    $tbegin = microtime(TRUE);
    $CNML->addAttribute('version', '0.1');
    $CNML->addAttribute('server_id', '1');
    $CNML->addAttribute('server_url', 'http://guifi.net');
    $CNML->addAttribute('generated', date('Ymd hi', time()));
    $CNML->addAttribute('description', 'ospf zone networks');
    $nodesid["{$cnmlid}"] = "";
    $nodes[] = $cnmlid;
    //busqueda de nodes de la zona ospf
    $tnodes = 0;
    while (isset($nodes[$n])) {
        $tnodes = $tnodes + ospf_net_search_links($nodes, $nodesid, $nodes[$n]);
        if ($tnodes < $nmax) {
            $n++;
        } else {
            break;
        }
    }
    ksort($nodesid);
    //busqueda de dades node, subxarxes de cada node, llista de zones
    $nreg = count($nodes);
    for ($n = 0; $n < $nreg; $n++) {
        $result = db_query(sprintf("SELECT t1.nick as nnick, t1.zone_id as zid, t2.nick as znick\n               FROM guifi_location as t1\n               join guifi_zone as t2 on t1.zone_id = t2.id\n               where t1.id = (%s)", $nodes[$n]));
        if ($record = db_fetch_object($result)) {
            $nodesid["{$nodes[$n]}"] = array("nnick" => $record->nnick, "zid" => $record->zid);
            if (!isset($azones[$record->zid])) {
                $azones[$record->zid] = $record->znick;
            }
        }
        ospf_net_add_node_networks($networks, $nodes[$n]);
    }
    ksort($networks);
    //busqueda de xarxes de la zona
    if (count($azones)) {
        foreach ($azones as $key => $azone) {
            $result = db_query(sprintf("SELECT t1.base as netid, t1.mask as mask\n               FROM guifi_networks as t1\n               where t1.zone = (%s)", $key));
            while ($record = db_fetch_object($result)) {
                $a = _ipcalc($record->netid, $record->mask);
                $splitip = explode(".", $a["netid"]);
                $c = $splitip[0] * pow(256, 3) + $splitip[1] * pow(256, 2) + $splitip[2] * 256 + $splitip[3];
                if (!isset($aznets[$c])) {
                    $aznets[$c] = array("netid" => $a["netid"], "maskbits" => $a["maskbits"], "broadcast" => $a["broadcast"], "zid" => $key, "swagr" => 0);
                } elseif ($aznets[$c]["maskbits"] > $a["maskbits"]) {
                    $aznets[$c] = array("netid" => $a["netid"], "maskbits" => $a["maskbits"], "broadcast" => $a["broadcast"], "zid" => $key, "swagr" => 0);
                }
            }
        }
    }
    ksort($aznets);
    //verifica que les xarxes de zona estiguin als nodes de la zona ospf
    $result = db_query("SELECT ipv4, netmask FROM {guifi_ipv4} where ipv4_type = 1");
    while ($ip = db_fetch_array($result)) {
        if ($ip['ipv4'] != 'dhcp' and !empty($ip['ipv4'])) {
            $ip_dec = ip2long($ip['ipv4']);
            $min = FALSE;
            $max = FALSE;
            if (!isset($ips[$ip_dec])) {
                // save memory by storing just the maskbits
                // by now, 1MB array contains 7,750 ips
                $ips[$ip_dec] = guifi_ipcalc_get_maskbits($ip['netmask']);
            }
        }
    }
    //agrupació de subxarxes
    $subnets = array_values($networks);
    for ($nmaskbits = 30; $nmaskbits > 16; $nmaskbits--) {
        $net1 = "";
        $knet1 = 0;
        $nreg = 0;
        if (count($subnets)) {
            foreach ($subnets as $key => $subnet) {
                if ($subnet["maskbits"] == $nmaskbits) {
                    $nreg++;
                    $a = _ipcalc_by_netbits($subnet["netid"], $nmaskbits - 1);
                    if ($a["netid"] != $net1) {
                        $net1 = $a["netid"];
                        $knet1 = $key;
                    } else {
                        $subnets[$knet1]["maskbits"] = $nmaskbits - 1;
                        unset($subnets[$key]);
                        $net1 = "";
                        $knet1 = 0;
                    }
                } else {
                    $net1 = "";
                    $knet1 = 0;
                }
            }
        }
        //if($nreg==0){
        //   break;
        //}
    }
    //   $networks[$c]=Array("ipv4" => $record->ipv4,"netmask" => $record->netmask,"netid" => $a["netid"],"maskbits" => $a["maskbits"],"nid" => $nid);
    //generació cnml
    $classXML0 = $CNML->addChild('aggregate_networks');
    $nreg = 0;
    if (count($subnets)) {
        foreach ($subnets as $key => $subnet) {
            $nreg++;
            $reg = $classXML0->addChild('subnet');
            $reg->addAttribute('address', $subnet["netid"]);
            $reg->addAttribute('maskbits', $subnet["maskbits"]);
        }
    }
    $classXML0->addAttribute('total_aggregate_networks', $nreg);
    $classXML = $CNML->addChild('networks');
    $nreg = 0;
    if (count($networks)) {
        foreach ($networks as $key => $network) {
            $nreg++;
            $reg = $classXML->addChild('subnet');
            $reg->addAttribute('num', $key);
            $reg->addAttribute('address', $network["netid"]);
            $reg->addAttribute('maskbits', $network["maskbits"]);
            $reg->addAttribute('node', $network["nid"]);
            $reg->addAttribute('nick', $nodesid[$network["nid"]]["nnick"]);
        }
    }
    $classXML->addAttribute('total_networks', $nreg);
    $classXML2 = $CNML->addChild('area_nodes');
    $nreg = 0;
    if (count($nodesid)) {
        foreach ($nodesid as $key => $nodeid) {
            $nreg++;
            $reg = $classXML2->addChild('node');
            $reg->addAttribute('node', $key);
            $reg->addAttribute('nick', $nodeid["nnick"]);
            $reg->addAttribute('zone', $azones[$nodeid["zid"]]);
        }
    }
    $classXML2->addAttribute('total_nodes', $nreg);
    $classXML3 = $CNML->addChild('zone_networks');
    $nreg = 0;
    if (count($aznets)) {
        foreach ($aznets as $key => $aznet) {
            $nreg++;
            $reg = $classXML3->addChild('subnet');
            //$reg->addAttribute('num',$key);
            $reg->addAttribute('address', $aznet["netid"]);
            $reg->addAttribute('maskbits', $aznet["maskbits"]);
            $reg->addAttribute('broadcast', $aznet["broadcast"]);
            $reg->addAttribute('zone', $azones[$aznet["zid"]]);
        }
    }
    $classXML3->addAttribute('total_zone_networks', $nreg);
    $CNML->addAttribute('elapsed', round(microtime(TRUE) - $tbegin, 4));
    return $CNML;
}
function guifi_kamikaze_files($dev, $zone)
{
    //SOME VARIABLES
    $dns = guifi_get_dns($zone, 2);
    $lan = guifi_unsolclic_if($dev->id, 'wLan/Lan');
    $lan_network = _ipcalc($lan->ipv4, $lan->netmask);
    switch ($dev->variable['model_id']) {
        case "39":
            // Avila GW2348-4
            $wireless_model = 'atheros';
            $lan_iface = 'eth0';
            $lan2_iface = 'eth1';
            $packages = 'ixp4xx/packages';
            break;
        default:
            _outln_comment('model id not supported');
            exit;
    }
    // SECTION FILES
    _outln_comment();
    _outln_comment();
    _outln_comment(t('File /etc/config/wireless'));
    function wds_add($dev, $radio)
    {
        $wds_links = array();
        foreach ($radio[interfaces] as $interface_id => $interface) {
            if ($interface[interface_type] == 'wds/p2p') {
                foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                    foreach ($ipv4[links] as $link_id => $link) {
                        if ($link['link_type'] == 'wds') {
                            $wds_links[] = $link;
                        }
                    }
                }
                $ifcount = 0;
                foreach ($wds_links as $key => $wds) {
                    if (preg_match("/(Working|Testing|Building)/", $wds['flag'])) {
                        $status = 'active';
                        print '        option \'wds_add' . $ifcount . '\' \'' . $wds['interface']['mac'] . '\'<br />';
                        $ifcount++;
                    } else {
                        $status = 'disabled';
                        print '# option \'wds_addX\' \'' . $wds['interface']['mac'] . '\'# ' . t($wds['flag']) . '<br />';
                    }
                }
            }
        }
    }
    function wds_network($dev, $radio)
    {
        $ifcount = '0';
        foreach ($radio[interfaces] as $interface_id => $interface) {
            foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                foreach ($ipv4[links] as $link_id => $link) {
                    if ($link['link_type'] == 'wds') {
                        $wds_links = array();
                        $wds_links[] = $link;
                        foreach ($wds_links as $key => $wds) {
                            $hostname = guifi_get_hostname($wds['device_id']);
                            if (preg_match("/(Working|Testing|Building)/", $wds['flag'])) {
                                $status = 'active';
                                print '
## wds_' . $hostname . '
config \'interface\' \'wds_' . $hostname . '\'
        option \'ifname\' \'ath' . $radio[radiodev_counter] . '.wds' . $ifcount . '\'
        option \'proto\' \'static\'
';
                                $ifcount++;
                            } else {
                                $status = 'disabled';
                                print '
##### ' . t($wds['flag']) . ' ####
## wds_' . $hostname . '
# config \'interface\' \'ath' . $radio[radiodev_counter] . '.wdsX\'
#       option \'proto\' \'none\'
';
                            }
                        }
                        if ($status == 'active') {
                            print '        option \'ipaddr\' \'' . $ipv4[ipv4] . '\'
        option \'netmask\' \'' . $ipv4['netmask'] . '\'
';
                        } else {
                            print '#       option \'ipaddr\' \'' . $ipv4[ipv4] . '\'
#       option \'netmask\' \'' . $ipv4['netmask'] . '\'
';
                        }
                    }
                }
            }
        }
    }
    function cable_network($dev)
    {
        foreach ($dev->interfaces as $interface_id => $interface) {
            switch ($interface[interface_type]) {
                case 'vlan1':
                    $iname = 'eth0:1';
                    break;
                case 'vlan2':
                    $iname = 'eth1';
                    break;
                case 'vlan3':
                    $iname = 'eth2';
                    break;
                default:
                    $iname = $interface[interface_type];
                    break;
            }
            foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                foreach ($ipv4[links] as $link_id => $link) {
                    $network = guifi_get_hostname($link[device_id]);
                    if (preg_match("/(Working|Testing|Building)/", $link['flag'])) {
                        $status = 'active';
                        if ($interface[interface_type] != 'wLan/Lan') {
                            print '
## cable_' . $network . '
config \'interface\' \'' . $network . '\'
        option \'ifname\'   \'' . $iname . '\'
';
                            print '        option \'proto\'    \'static\'
        option \'ipaddr\'   \'' . $ipv4[ipv4] . '\'
        option \'netmask\'  \'' . $ipv4[netmask] . '\'

';
                        }
                    } else {
                        $status = 'disabled';
                        print '
##### ' . t($link['flag']) . ' ####
## cable_' . $network . '
# config \'interface\' \'' . $network . '\'
#        option \'ifname\'   \'' . $iname . '\'
';
                        print '#        option \'proto\'    \'static\'
#        option \'ipaddr\'   \'' . $ipv4[ipv4] . '\'
#        option \'netmask\'  \'' . $ipv4[netmask] . '\'

';
                    }
                }
            }
        }
    }
    print '<pre>
echo "
';
    if (isset($dev->radios)) {
        foreach ($dev->radios as $radio_id => $radio) {
            $mode = 'ap';
            $ssid = $radio[ssid];
            $channel = atheros_channel($radio);
            if ($channel < 14) {
                $band = '11b';
            } else {
                $band = '11a';
            }
            if (empty($radio[antenna_mode])) {
                $radio[antenna_mode] = '1';
            } else {
                if ($radio[antenna_mode] != 'Main') {
                    $radio[antenna_mode] = '2';
                } else {
                    $radio[antenna_mode] = '1';
                }
            }
            if ($radio_id == '0') {
                $wireless_iface = 'wifi0';
                $network = 'lan';
            } else {
                $wireless_iface = 'wifi' . $radio_id;
                $network = 'wlan' . ($radio_id + 1);
            }
            $wireless_model = 'atheros';
            $txant = 'txantenna';
            $rxant = 'rxantenna';
            print '
## Radio: ' . $radio[ssid] . '
config \'wifi-device\' \'' . $wireless_iface . '\'
        option \'type\' \'' . $wireless_model . '\'
        option \'channel\' \'' . $channel . '\'
        option \'disabled\' \'0\'
        option \'hwmode\' \'' . $band . '\'
        option \'diversity\' \'0\'
        option \'' . $txant . '\' \'' . $radio[antenna_mode] . '\'
        option \'' . $rxant . '\' \'' . $radio[antenna_mode] . '\'
        option \'txpower\' \'16\'

config wifi-iface
        option \'device\' \'' . $wireless_iface . '\'
        option \'network\' \'' . $network . '\'
        option \'agmode\' \'' . $mode . '\'
        option \'ssid\' \'guifi.net-' . $radio[ssid] . '\'
        option \'encryption\' \'none\'
';
            wds_add($dev, $radio);
        }
    }
    print '
" > /etc/config/wireless </pre>
';
    _outln_comment();
    _outln_comment();
    _outln_comment(t('File /etc/config/network'));
    print '<pre>
echo "
config interface loopback
        option \'ifname\'  \'lo\'
        option \'proto\'    \'static\'
        option \'ipaddr\'   \'127.0.0.1\'
        option \'netmask\'  \'255.0.0.0\'

';
    if (isset($dev->radios)) {
        foreach ($dev->radios as $radio_id => $radio) {
            if (isset($radio[interfaces])) {
                foreach ($radio[interfaces] as $interface_id => $interface) {
                    if ($interface[interface_type] != 'wds/p2p') {
                        if (isset($interface[ipv4])) {
                            foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                                if ($interface[interface_type] == 'wLan/Lan') {
                                    $iface = 'ath0 eth0';
                                    $network = 'lan';
                                } else {
                                    $iface = 'wifi' . $radio_id;
                                    $network = 'wlan' . ($radio_id + 1);
                                }
                                $item = _ipcalc($ipv4[ipv4], $ipv4[netmask]);
                                // FILE NETWORK
                                print '
config interface ' . $network . '
        option \'ifname\'   \'' . $iface . '\'
';
                                if ($interface[interface_type] == 'wLan/Lan') {
                                    print '        option \'type\'     \'bridge\'
';
                                }
                                print '        option \'proto\'    \'static\'
        option \'ipaddr\'   \'' . $ipv4[ipv4] . '\'
        option \'netmask\'  \'' . $ipv4[netmask] . '\'
        option \'dns\'      \'' . $dns . '\'

';
                            }
                        }
                    }
                }
            }
            wds_network($dev, $radio);
        }
    }
    cable_network($dev);
    print '
" > /etc/config/network </pre>
';
    $wds_links = array();
    foreach ($dev->radios as $radio_id => $radio) {
        foreach ($radio[interfaces] as $interface_id => $interface) {
            if ($interface[interface_type] == 'wds/p2p') {
                foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                    foreach ($ipv4[links] as $link_id => $link) {
                        if ($link['link_type'] == 'wds') {
                            $wds_links[] = $link;
                        }
                    }
                }
            }
        }
    }
    foreach ($wds_links as $key => $wds) {
        if ($wds['routing'] == 'BGP') {
            $wds_bgpd = '1';
        }
        if ($wds['routing'] == 'OSPF') {
            $wds_ospfd = '1';
        }
    }
    $cable_links = array();
    foreach ($dev->interfaces as $interface_id => $interface) {
        foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
            foreach ($ipv4[links] as $link_id => $link) {
                if ($link['link_type'] == 'cable') {
                    $cable_links[] = $link;
                }
            }
        }
    }
    foreach ($cable_links as $key => $cable) {
        if ($cable['routing'] == 'BGP') {
            $cable_bgpd = '1';
        }
        if ($cable['routing'] == 'OSPF') {
            $cable_ospfd = '1';
        }
    }
    // QUAGGA CONFIG FILES
    $file_zebra = '';
    _outln_comment();
    _outln_comment();
    _outln_comment(t('File /etc/quagga/zebra.conf'));
    _out_file($file_zebra, '/etc/quagga/zebra.conf');
    // FILE OSPFD
    if ($wds_ospfd == '1' || $cable_ospfd == '1') {
        _outln_comment();
        _outln_comment();
        _outln_comment(t('File /etc/quagga/ospfd.conf'));
        print '<pre>mv /etc/quagga/ospfd.conf /etc/quagga/ospfd.conf.bak
echo "
!
interface br-lan
!
router ospf
 ospf router-id ' . $lan->ipv4 . '
 redistribute bgp
';
        foreach ($dev->radios as $radio_id => $radio) {
            foreach ($radio[interfaces] as $interface_id => $interface) {
                if ($interface[interface_type] == 'wLan' || $interface[interface_type] == 'wLan/Lan') {
                    foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                        $network = _ipcalc($ipv4[ipv4], $ipv4[netmask]);
                    }
                    if (preg_match("/(Working|Testing|Building)/", $link['flag'])) {
                        print ' network ' . $network[netid] . '/' . $network[maskbits] . ' area 0<br />';
                    }
                }
            }
        }
        foreach ($wds_links as $key => $wds) {
            $iplocal[] = $wds['interface']['ipv4'];
            if ($wds['routing'] == 'OSPF') {
                $wds_network = _ipcalc($iplocal[$key][ipv4], $iplocal[$key][netmask]);
                if (preg_match("/(Working|Testing|Building)/", $wds['flag'])) {
                    print ' network ' . $wds_network[netid] . '/' . $wds_network[maskbits] . ' area 0<br />';
                }
            }
        }
        foreach ($dev->interfaces as $interface_id => $interface) {
            foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                foreach ($ipv4[links] as $link_id => $link) {
                    $item = _ipcalc($ipv4[ipv4], $ipv4[netmask]);
                    if ($link['routing'] == 'OSPF') {
                        if (preg_match("/(Working|Testing|Building)/", $link['flag'])) {
                            print ' network ' . $item[netid] . '/' . $item[maskbits] . ' area 0<br />';
                        }
                    }
                }
            }
        }
        print 'default-information originate
!
" > /etc/quagga/ospfd.conf</pre>';
    }
    // FILE BGPD
    if ($wds_bgpd == '1' || $cable_bgpd == '1') {
        _outln_comment();
        _outln_comment();
        _outln_comment(t('File /etc/quagga/bgpd.conf'));
        print '<pre>mv /etc/quagga/bgpd.conf /etc/quagga/bgpd.conf.bak
echo "
!
interface br-lan
!
router bgp ' . $dev->id . '
bgp router-id ' . $lan->ipv4 . '
';
        foreach ($dev->radios as $radio_id => $radio) {
            foreach ($radio[interfaces] as $interface_id => $interface) {
                if ($interface[interface_type] == 'wLan' || $interface[interface_type] == 'wLan/Lan') {
                    foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                        $network = _ipcalc($ipv4[ipv4], $ipv4[netmask]);
                    }
                    print ' network ' . $network[netid] . '/' . $network[maskbits] . '<br />';
                }
            }
        }
        print 'redistribute ospf
';
        foreach ($wds_links as $key => $wds) {
            $iplocal[] = $wds['interface']['ipv4'];
            if ($wds['routing'] == 'BGP') {
                $wds_network = _ipcalc($iplocal[$key][ipv4], $iplocal[$key][netmask]);
                if (preg_match("/(Working|Testing|Building)/", $wds['flag'])) {
                    print ' network ' . $wds_network[netid] . '/' . $wds_network[maskbits] . '<br />';
                }
            }
        }
        foreach ($dev->interfaces as $interface_id => $interface) {
            foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                foreach ($ipv4[links] as $link_id => $link) {
                    $item = _ipcalc($ipv4[ipv4], $ipv4[netmask]);
                    if ($link['routing'] == 'BGP') {
                        if (preg_match("/(Working|Testing|Building)/", $link['flag'])) {
                            print ' network ' . $item[netid] . '/' . $item[maskbits] . '<br />';
                        }
                    }
                }
            }
        }
        foreach ($dev->radios as $radio_id => $radio) {
            foreach ($radio[interfaces] as $interface_id => $interface) {
                foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                    foreach ($ipv4[links] as $link_id => $link) {
                        if ($link['routing'] == 'BGP') {
                            if (preg_match("/(Working|Testing|Building)/", $link['flag'])) {
                                print ' neighbor ' . $link['interface']['ipv4']['ipv4'] . ' remote-as ' . $link['device_id'] . '
';
                            }
                        }
                    }
                }
            }
        }
        foreach ($dev->interfaces as $interface_id => $interface) {
            foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                foreach ($ipv4[links] as $link_id => $link) {
                    if ($link['routing'] == 'BGP') {
                        if (preg_match("/(Working|Testing|Building)/", $link['flag'])) {
                            print ' neighbor ' . $link['interface']['ipv4']['ipv4'] . ' remote-as ' . $link['device_id'] . '
';
                        }
                    }
                }
            }
        }
        print '" > /etc/quagga/bgpd.conf</pre>';
    }
    //FILE FIREWALL
    _outln_comment();
    _outln_comment();
    _outln_comment(t('File /etc/config/firewall'));
    print '<pre>
echo "
config defaults
        option \'syn_flood\' \'1\'
        option \'input\' \'ACCEPT\'
        option \'output\' \'ACCEPT\'
        option \'forward\' \'ACCEPT\'
';
    foreach ($dev->radios as $radio_id => $radio) {
        foreach ($radio[interfaces] as $interface_id => $interface) {
            if ($interface[interface_type] == 'wLan' || $interface[interface_type] == 'wLan/Lan') {
                foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                    if ($interface[interface_type] == 'wLan/Lan') {
                        $network = 'lan';
                    } else {
                        $network = 'wlan' . ($radio_id + 1);
                    }
                    print '        
config zone
        option \'name\' \'' . $network . '\'
        option \'input\' \'ACCEPT\'
        option \'output\' \'ACCEPT\'
        option \'forward\' \'ACCEPT\'

';
                }
            }
        }
    }
    if ($interface[interface_type] == 'wds/p2p') {
        foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
            foreach ($ipv4[links] as $link_id => $link) {
                if ($link['link_type'] == 'wds') {
                    $ifcount = 0;
                }
            }
        }
    }
    foreach ($wds_links as $key => $wds) {
        $hostname = guifi_get_hostname($wds['device_id']);
        if (preg_match("/(Working|Testing|Building)/", $wds['flag'])) {
            print '        
config zone
        option \'name\' \'wds_' . $hostname . '\'
        option \'input\' \'ACCEPT\'
        option \'output\' \'ACCEPT\'
        option \'forward\' \'ACCEPT\'

';
        }
    }
    foreach ($dev->interfaces as $interface_id => $interface) {
        foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
            foreach ($ipv4[links] as $link_id => $link) {
                $hostname = guifi_get_hostname($link['device_id']);
                if (preg_match("/(Working|Testing|Building)/", $link['flag'])) {
                    print '        
config zone
        option \'name\' \'' . $hostname . '\'
        option \'input\' \'ACCEPT\'
        option \'output\' \'ACCEPT\'
        option \'forward\' \'ACCEPT\'

';
                }
            }
        }
    }
    print '" > /etc/config/firewall</pre>';
    //FILE OPKG
    $opkg_conf = '
src/gz snapshots http://downloads.openwrt.org/snapshots/' . $packages . '
dest root /
dest ram /tmp
lists_dir ext /var/opkg-lists
option overlay_root /jffs
';
    _outln_comment();
    _outln_comment();
    _outln_comment(t('File /etc/opkg.conf'));
    _out_file($opkg_conf, '/etc/opkg.conf');
    $dhcp_statics = array();
    $max = explode(".", $dev->ipv4);
    function merge_static($link, &$dhcp_statics, &$max, &$curr)
    {
        if (empty($link['interface'][mac])) {
            $link['interface'][mac] = 'FF:FF:FF:FF:FF:FF';
        }
        $dhcp_statics[] = array($link['interface'][ipv4][ipv4], $link['interface'][mac], guifi_get_hostname($link['interface'][device_id]));
        $curr = explode(".", $link['interface'][ipv4][ipv4]);
        if ($curr[3] > $max[3]) {
            $max[3] = $curr[3];
        }
    }
    $main_ip = guifi_main_ip($dev->id);
    $item = _ipcalc_by_netbits($main_ip[ipv4], $main_ip[maskbits]);
    $max = explode(".", $main_ip[ipv4]);
    // cable links
    foreach ($dev->interfaces as $interface) {
        foreach ($interface[ipv4] as $ipv4) {
            foreach ($ipv4[links] as $link) {
                if ($link['interface'][ipv4][ipv4] != '') {
                    $item2 = _ipcalc($link['interface'][ipv4][ipv4], $link['interface'][ipv4][netmask]);
                    if ($item[netid] == $item2[netid]) {
                        merge_static($link, $dhcp_statics, $max, $cur);
                    }
                }
            }
        }
    }
    // ap/client links
    foreach ($dev->radios as $radio) {
        foreach ($radio[interfaces] as $interface) {
            foreach ($interface[ipv4] as $ipv4) {
                foreach ($ipv4[links] as $link) {
                    if ($link['link_type'] == 'ap/client' and !empty($link['interface'][ipv4][ipv4])) {
                        merge_static($link, $dhcp_statics, $max, $cur);
                    }
                }
            }
        }
    }
    $statics = count($dhcp_statics) - 1;
    $totalstatics = count($dhcp_statics);
    $first = explode(".", $item[netid]);
    $last = explode(".", $item[broadcast]);
    $limit = $last[3] - 1 - ($first[3] + 3) - $totalstatics;
    _outln_comment();
    _outln_comment(t('File /etc/config/luci_ethers'));
    print 'echo "';
    foreach ($dhcp_statics as $static) {
        print '<pre>
## Device: ' . $static[2] . '
config \'static_lease\'
        option \'macaddr\' \'' . $static[1] . '\'
        option \'ipaddr\' \'' . $static[0] . '\'
</pre>';
    }
    print '" > /etc/config/luci_ethers<br />';
    // FILE DHCP
    _outln_comment();
    _outln_comment();
    _outln_comment(t('File /etc/config/dhcp'));
    print '<pre>
echo "
config \'dnsmasq\'
        option \'domainneeded\' \'1\'
        option \'boguspriv\' \'1\'
        option \'filterwin2k\' \'0\'
        option \'localise_queries\' \'1\'
        option \'local\' \'/lan/\'
        option \'domain\' \'lan\'
        option \'expandhosts\' \'1\'
        option \'nonegcache\' \'0\'
        option \'authoritative\' \'1\'
        option \'readethers\' \'1\'
        option \'leasefile\' \'/tmp/dhcp.leases\'
        option \'resolvfile\' \'/tmp/resolv.conf.auto\'
';
    foreach ($dev->radios as $radio_id => $radio) {
        foreach ($radio[interfaces] as $interface_id => $interface) {
            if ($interface[interface_type] == 'wLan' || $interface[interface_type] == 'wLan/Lan') {
                foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                    if ($interface[interface_type] == 'wLan/Lan') {
                        $iface = 'lan';
                        $network = 'lan';
                    } else {
                        $network = 'wlan' . ($radio_id + 1);
                    }
                    $max = explode(".", $ipv4[ipv4]);
                    foreach ($ipv4[links] as $link) {
                        if ($link['link_type'] == 'ap/client' and !empty($link['interface'][ipv4][ipv4])) {
                            $totalstaticss = count($ipv4[links]);
                        }
                    }
                    $first = explode(".", $item[netid]);
                    $last = explode(".", $item[broadcast]);
                    $limit = $last[3] - 1 - ($first[3] + 3) - $totalstaticss;
                    $totalstaticss = '0';
                    print '
 config \'dhcp\' \'' . $network . '\'
        option \'interface\' \'' . $network . '\'
        option \'leasetime\' \'12h\'
        option \'start\' \'' . ($max[3] + 2) . '\'
        option \'limit\' \'' . $limit . '\'
';
                }
            }
        }
    }
    print '" > /etc/config/dhcp<br /></pre>';
}
function guifi_routingmap_search($plat1, $plon1, $plat2, $plon2)
{
    $result = db_query(sprintf("SELECT t1.id as nid,t1.lat,t1.lon\n            FROM guifi_location as t1\n            where t1.status_flag='Working' and t1.lat between (%s) and (%s) and\n\t\t\t\t\t\tt1.lon between (%s) and (%s);", $plat1, $plat2, $plon1, $plon2));
    $cnmlid = 0;
    while ($record = db_fetch_object($result)) {
        $cnmlid = $record->nid;
        break;
    }
    $nmax = 200;
    //max nodes
    $networks = array();
    //array de subxarxes de la zona
    $nodes = array();
    //array sequential id nodes
    $nodesid = array();
    //array node data + repetition control
    $devices = array();
    //array sequential id devices
    $devicesid = array();
    //array devices repetition control
    $subnets = array();
    //array de subxarxes agrupades
    $azones = array();
    //array de zones implicades
    $aznets = array();
    //array de xarxes de les zones implicades
    $alinks = array();
    //Array links
    $nreg = 0;
    $n = 0;
    $nodesid["{$cnmlid}"] = "";
    $nodes[] = $cnmlid;
    //Search first device
    $tnodes = 0;
    if (isset($nodes[$n])) {
        $v = guifi_routingmap_search_firstdevice($nodes[$n]);
        if ($v > 0) {
            $devices[] = $v;
            $devicesid["{$v}"] = $nodes[$n];
        }
    }
    //Devices for ospf area
    $tnodes = 1;
    $n = 0;
    while (isset($devices[$n])) {
        $tnodes = $tnodes + guifi_routingmap_search_links($nodes, $nodesid, $devices, $devicesid, $alinks, $devices[$n]);
        if ($tnodes < $nmax) {
            $n++;
        } else {
            break;
        }
    }
    ksort($devicesid);
    ksort($nodesid);
    //search device subnets
    $nreg = count($devices);
    for ($n = 0; $n < $nreg; $n++) {
        guifi_routingmap_add_device_networks($networks, $devices[$n], $devicesid["{$devices[$n]}"]);
    }
    ksort($networks);
    //search node data, zone list
    $nreg = count($nodes);
    for ($n = 0; $n < $nreg; $n++) {
        $result = db_query(sprintf("SELECT t1.nick as nnick, t1.zone_id as zid, t1.lat, t1.lon, t2.nick as znick\n               FROM guifi_location as t1\n               join guifi_zone as t2 on t1.zone_id = t2.id \n               where t1.id = (%s)", $nodes[$n]));
        if ($record = db_fetch_object($result)) {
            $nodesid["{$nodes[$n]}"] = array("nnick" => $record->nnick, "zid" => $record->zid, "lat" => $record->lat, "lon" => $record->lon);
            if (!isset($azones[$record->zid])) {
                $azones[$record->zid] = $record->znick;
            }
        }
    }
    //search zone subnets
    if (count($azones)) {
        foreach ($azones as $key => $azone) {
            $result = db_query(sprintf("SELECT t1.base as netid, t1.mask as mask\n               FROM guifi_networks as t1\n               where t1.zone = (%s)", $key));
            while ($record = db_fetch_object($result)) {
                $a = _ipcalc($record->netid, $record->mask);
                $splitip = explode(".", $a["netid"]);
                $c = $splitip[0] * pow(256, 3) + $splitip[1] * pow(256, 2) + $splitip[2] * 256 + $splitip[3];
                if (!isset($aznets[$c])) {
                    $aznets[$c] = array("netid" => $a["netid"], "maskbits" => $a["maskbits"], "broadcast" => $a["broadcast"], "zid" => $key, "swagr" => 0, "znick" => $azone, "intnetid" => ip2long($a["netid"]), "intbroadcast" => ip2long($a["broadcast"]));
                } elseif ($aznets[$c]["maskbits"] > $a["maskbits"]) {
                    $aznets[$c] = array("netid" => $a["netid"], "maskbits" => $a["maskbits"], "broadcast" => $a["broadcast"], "zid" => $key, "swagr" => 0, "znick" => $azone, "intnetid" => ip2long($a["netid"]), "intbroadcast" => ip2long($a["broadcast"]));
                }
            }
        }
    }
    ksort($aznets);
    //agregate subnets
    $subnets = array();
    foreach ($networks as $key => $network) {
        $subnets[$key] = array("netid" => $network["netid"], "maskbits" => $network["maskbits"]);
    }
    //$subnets=array_values($networks);
    for ($nmaskbits = 30; $nmaskbits > 16; $nmaskbits--) {
        $net1 = "";
        $knet1 = 0;
        $nreg = 0;
        if (count($subnets)) {
            foreach ($subnets as $key => $subnet) {
                if ($subnet["maskbits"] == $nmaskbits) {
                    $nreg++;
                    $a = _ipcalc_by_netbits($subnet["netid"], $nmaskbits - 1);
                    if ($a["netid"] != $net1) {
                        $net1 = $a["netid"];
                        $knet1 = $key;
                    } else {
                        $subnets[$knet1]["maskbits"] = $nmaskbits - 1;
                        unset($subnets[$key]);
                        $net1 = "";
                        $knet1 = 0;
                    }
                } else {
                    $net1 = "";
                    $knet1 = 0;
                }
            }
        }
    }
    //search networks in zone networks
    $aggregate = array();
    foreach ($networks as $key => $network) {
        $a = _ipcalc($network["ipv4"], $network["netmask"]);
        $b = ip2long($a["netid"]);
        $z = ip2long($a["broadcast"]);
        //return json_encode(array($a,$b,$z));
        $sw = 0;
        foreach ($aznets as $zkey => $znet) {
            if ($b >= $znet["intnetid"] && $z <= $znet["intbroadcast"]) {
                $sw = 1;
                break;
            }
        }
        if ($sw == 0) {
            $aggregate[$key] = array("netid" => $network["netid"], "maskbits" => $network["maskbits"], "zone" => "");
        }
    }
    //aggregate subnets ultimate
    foreach ($aznets as $key => $znet) {
        $aggregate[$key] = array("netid" => $znet["netid"], "maskbits" => $znet["maskbits"], "zone" => "zone");
    }
    ksort($aggregate);
    for ($nmaskbits = 30; $nmaskbits > 16; $nmaskbits--) {
        $net1 = "";
        $knet1 = 0;
        $nreg = 0;
        if (count($aggregate)) {
            foreach ($aggregate as $key => $subnet) {
                if ($subnet["maskbits"] == $nmaskbits) {
                    $nreg++;
                    $a = _ipcalc_by_netbits($subnet["netid"], $nmaskbits - 1);
                    if ($a["netid"] != $net1) {
                        $net1 = $a["netid"];
                        $knet1 = $key;
                    } else {
                        $aggregate[$knet1]["maskbits"] = $nmaskbits - 1;
                        unset($aggregate[$key]);
                        $net1 = "";
                        $knet1 = 0;
                    }
                } else {
                    $net1 = "";
                    $knet1 = 0;
                }
            }
        }
    }
    return json_encode(array($cnmlid, $nodesid, $alinks, $subnets, $aznets, $aggregate));
    //   $networks[$c]=Array("ipv4" => $record->ipv4,"netmask" => $record->netmask,"netid" => $a["netid"],"maskbits" => $a["maskbits"],"nid" => $nid);
}
function guifi_kamikaze_files($dev, $zone)
{
    //SOME VARIABLES
    $lan = guifi_unsolclic_if($dev->id, 'wLan/Lan');
    $wan = guifi_unsolclic_if($dev->id, 'Wan');
    $dns = guifi_get_dns($zone, 2);
    $wireless_model = 0;
    $wireless_iface = 0;
    switch ($dev->variable['model_id']) {
        case "1":
        case "15":
        case "16":
        case "17":
        case "18":
            // WRT54Gv1-4, WHR-HP-G54, WHR-G54S (BUFFALO), WRT54GL, WRT54GSv1-2, WRT54GSv4
            $wireless_model = 'broadcom';
            $wireless_iface = 'wl0';
            $vlans = 'config switch eth0
        option vlan0    \\"1 2 3 4 5*\\"
        option vlan1    \\"0 5\\"
      ';
            $lan_iface = 'eth0.0';
            $wan_iface = 'eth0.1';
            $txant = 'txant';
            $rxant = 'rxant';
            $packages = 'broadcom/packages';
            break;
        default:
            _outln_comment('model id not supported');
            exit;
    }
    if (empty($dev->radios[0][antenna_mode])) {
        $dev->radios[0][antenna_mode] = 'Main';
    }
    if ($dev->radios[0][antenna_mode] != 'Main') {
        $dev->radios[0][antenna_mode] = '1';
    } else {
        $dev->radios[0][antenna_mode] = '0';
    }
    $wds_links = array();
    $wds_str = '';
    foreach ($dev->radios as $radio_id => $radio) {
        foreach ($radio[interfaces] as $interface_id => $interface) {
            if ($interface['interface_type'] == 'wds/p2p') {
                foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                    foreach ($ipv4[links] as $key => $link) {
                        if ($link['link_type'] == 'wds') {
                            $wds_links[] = $link;
                        }
                        $iplocal[] = $ipv4;
                        $iflocal[] = $interface;
                    }
                }
            }
        }
    }
    if (count($wds_links) == 0) {
        return;
    }
    // SECTION FILES
    // FILE NETWORK
    $lan_network = _ipcalc($lan->ipv4, $lan->netmask);
    $file_network = '
' . $vlans . '
config interface loopback
        option \'ifname\'  \'lo\'
        option \'proto\'    \'static\'
        option \'ipaddr\'   \'127.0.0.1\'
        option \'netmask\'  \'255.0.0.0\'

config interface lan
        option \'ifname\'   \'' . $lan_iface . '\'
        option \'type\'     \'bridge\'
        option \'proto\'    \'static\'
        option \'ipaddr\'   \'' . $lan->ipv4 . '\'
        option \'netmask\'  \'' . $lan->netmask . '\'
        option \'gateway\'  \'0.0.0.0\'
        option \'dns\'      \'' . $dns . '\'

config interface wan
        option \'ifname\'   \'' . $wan_iface . '\'
        option \'proto\'    \'none\'
        
';
    _outln_comment();
    _outln_comment();
    _outln_comment(t('File /etc/config/network'));
    _out_file($file_network, '/etc/config/network');
    // FILE WIRELESS
    $file_wireless = '
config \'wifi-device\' \'' . $wireless_iface . '\'
        option \'type\' \'' . $wireless_model . '\'
        option \'channel\' \'' . $dev->radios[0][channel] . '\'
        option \'disabled\' \'0\'
        option \'' . $txant . '\' \'' . $dev->radios[0][antenna_mode] . '\'
        option \'' . $rxant . '\' \'' . $dev->radios[0][antenna_mode] . '\'

config wifi-iface
        option \'device\' \'' . $wireless_iface . '\'
        option \'network\' \'lan\'
        option \'mode\' \'ap\'
        option \'ssid\' \'guifi.net-' . guifi_to_7bits($dev->radios[0][ssid]) . '\'
        option \'encryption \'none\'
';
    _outln_comment();
    _outln_comment();
    _outln_comment(t('File /etc/config/wireless'));
    _out_file($file_wireless, '/etc/config/wireless');
    // WDS Links
    $ifcount = 1;
    foreach ($wds_links as $key => $wds) {
        $hostname = guifi_get_hostname($wds['device_id']);
        if (preg_match("/(Working|Testing|Building)/", $wds['flag'])) {
            $status = 'active';
            if ($wds['routing'] == 'BGP') {
                $bgpd = '1';
            }
            if ($wds['routing'] == 'OSPF') {
                $ospfd = '1';
            }
            $ifcount++;
            $wds_won = 'option \'bssid\' \'' . $wds['interface']['mac'] . '\'';
            $wds_non = 'option \'proto\' \'static\'
        option \'ifname\' \'wds0.' . ($key + 1) . '\'
        option \'ipaddr\' \'' . $iplocal[$key][ipv4] . '\'
        option \'netmask\' \'' . $iplocal[$key][netmask] . '\'';
        } else {
            $status = 'disabled';
            $wds_won = 'option \'bssid\' \'00:00:00:00:00:00\'';
            $wds_non = 'option \'proto\' \'none\'';
        }
        $wds_network = 'config \'interface\' \'wds_' . $hostname . '\'
        ' . $wds_non . '
        ';
        $wds_wireless = 'config \'wifi-iface\'
        option \'device\' \'wl0\'
        option \'network\' \'wds_' . $hostname . '\'
        option \'mode\' \'wds\'
        option \'encryption\' \'none\'
        ' . $wds_won . '
        ';
        _outln_comment();
        _outln_comment('WDS ' . $hostname . '');
        _outln_comment('Routing: ' . $wds['routing'] . '');
        _outln_comment('Status: ' . $status . '');
        print '<pre>echo "' . $wds_network . '
" >> /etc/config/network
          </pre>';
        print '<pre>echo "' . $wds_wireless . '
" >> /etc/config/wireless
          </pre>';
    }
    if (count($wds_links) >= 5) {
        return;
    }
    // QUAGGA CONFIG FILES
    $file_zebra = '';
    _outln_comment();
    _outln_comment();
    _outln_comment(t('File /etc/quagga/zebra.conf'));
    _out_file($file_zebra, '/etc/quagga/zebra.conf');
    // FILE OSPFD
    if ($ospfd == '1') {
        _outln_comment();
        _outln_comment();
        _outln_comment(t('File /etc/quagga/ospfd.conf'));
        print '<pre>mv /etc/quagga/ospfd.conf /etc/quagga/ospfd.conf.bak
echo "
!
interface br-lan
!
router ospf
 ospf router-id ' . $lan->ipv4 . '
 redistribute bgp
 network ' . $lan_network[netid] . '/' . $lan_network[maskbits] . ' area 0<br />';
        foreach ($wds_links as $key => $wds) {
            if ($wds['routing'] == 'OSPF') {
                $wds_network = _ipcalc($iplocal[$key][ipv4], $iplocal[$key][netmask]);
                print ' network ' . $wds_network[netid] . '/' . $wds_network[maskbits] . ' area 0<br />';
            }
        }
        print 'default-information originate
!
" > /etc/quagga/ospfd.conf</pre>';
    }
    // FILE BGPD
    if ($bgpd == '1') {
        _outln_comment();
        _outln_comment();
        _outln_comment(t('File /etc/quagga/bgpd.conf'));
        print '<pre>mv /etc/quagga/bgpd.conf /etc/quagga/bgpd.conf.bak
echo "
!
interface br-lan
!
router bgp ' . $dev->id . '
bgp router-id ' . $lan->ipv4 . '
 network ' . $lan_network[netid] . '/' . $lan_network[maskbits] . '<br />';
        foreach ($wds_links as $key => $wds) {
            if ($wds['routing'] == 'BGP') {
                $wds_network = _ipcalc($iplocal[$key][ipv4], $iplocal[$key][netmask]);
                print ' network ' . $wds_network[netid] . '/' . $wds_network[maskbits] . '<br />';
            }
        }
        print 'redistribute ospf
';
        foreach ($dev->radios as $radio_id => $radio) {
            foreach ($radio[interfaces] as $interface_id => $interface) {
                foreach ($interface[ipv4] as $ipv4_id => $ipv4) {
                    foreach ($ipv4[links] as $link_id => $link) {
                        if ($link['routing'] == 'BGP') {
                            print 'neighbor ' . $link['interface']['ipv4']['ipv4'] . ' remote-as ' . $link['device_id'] . '
';
                        }
                    }
                }
            }
        }
        print '" > /etc/quagga/bgpd.conf</pre>';
    }
    //FILE FIREWALL
    $firewall = '
config defaults
        option \'syn_flood\' \'1\'
        option \'input\' \'ACCEPT\'
        option \'output\' \'ACCEPT\'
        option \'forward\' \'ACCEPT\'
        
config zone
        option \'name\' \'lan\'
        option \'input\' \'ACCEPT\'
        option \'output\' \'ACCEPT\'
        option \'forward\' \'ACCEPT\'

';
    _outln_comment();
    _outln_comment();
    _outln_comment(t('File /etc/config/firewall'));
    _out_file($firewall, '/etc/config/firewall');
    //FILE OPKG
    $opkg_conf = '
src/gz guifi http://ausa.guifi.net/drupal/files/openwrt/ap/' . $packages . '
dest root /
dest ram /tmp
lists_dir ext /var/opkg-lists
';
    _outln_comment();
    _outln_comment();
    _outln_comment(t('File /etc/opkg.conf'));
    _out_file($opkg_conf, '/etc/opkg.conf');
    $dhcp_statics = array();
    $max = explode(".", $dev->ipv4);
    function merge_static($link, &$dhcp_statics, &$max, &$curr)
    {
        if (empty($link['interface'][mac])) {
            $link['interface'][mac] = 'FF:FF:FF:FF:FF:FF';
        }
        $dhcp_statics[] = array($link['interface'][ipv4][ipv4], $link['interface'][mac], guifi_get_hostname($link['interface'][device_id]));
        $curr = explode(".", $link['interface'][ipv4][ipv4]);
        if ($curr[3] > $max[3]) {
            $max[3] = $curr[3];
        }
    }
    $main_ip = guifi_main_ip($dev->id);
    $item = _ipcalc_by_netbits($main_ip[ipv4], $main_ip[maskbits]);
    $max = explode(".", $main_ip[ipv4]);
    // cable links
    if (!empty($dev->interfaces)) {
        foreach ($dev->interfaces as $interface) {
            if (!empty($interface[ipv4])) {
                foreach ($interface[ipv4] as $ipv4) {
                    if (!empty($ipv4[links])) {
                        foreach ($ipv4[links] as $link) {
                            if ($link['interface'][ipv4][ipv4] != '') {
                                $item2 = _ipcalc($link['interface'][ipv4][ipv4], $link['interface'][ipv4][netmask]);
                                if ($item[netid] == $item2[netid]) {
                                    merge_static($link, $dhcp_statics, $max, $cur);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    // ap/client links
    if (!empty($dev->radios)) {
        foreach ($dev->radios as $radio) {
            if (!empty($radio[interfaces])) {
                foreach ($radio[interfaces] as $interface) {
                    if (!empty($interface[ipv4])) {
                        foreach ($interface[ipv4] as $ipv4) {
                            if (!empty($ipv4[links])) {
                                foreach ($ipv4[links] as $link) {
                                    if ($link['link_type'] == 'ap/client' and !empty($link['interface'][ipv4][ipv4])) {
                                        merge_static($link, $dhcp_statics, $max, $cur);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    $statics = count($dhcp_statics) - 1;
    $totalstatics = count($dhcp_statics);
    $first = explode(".", $item[netid]);
    $last = explode(".", $item[broadcast]);
    $limit = $last[3] - 1 - ($first[3] + 3) - $totalstatics;
    if ($statics == -1) {
        _outln_comment();
        _outln_comment(t('File /etc/config/luci_ethers'));
        _outln_nvram('dhcp_start', $max[3] + 2);
    }
    _outln_comment();
    _outln_comment(t('File /etc/config/luci_ethers'));
    print 'echo "';
    foreach ($dhcp_statics as $static) {
        print '<pre>
## Device: ' . $static[2] . '
config \'static_lease\'
        option \'macaddr\' \'' . $static[1] . '\'
        option \'ipaddr\' \'' . $static[0] . '\'
</pre>';
    }
    print '" > /etc/config/luci_ethers<br />';
    // FILE DHCP
    $file_dhcp = '
config \'dnsmasq\'
        option \'domainneeded\' \'1\'
        option \'boguspriv\' \'1\'
        option \'filterwin2k\' \'0\'
        option \'localise_queries\' \'1\'
        option \'local\' \'/lan/\'
        option \'domain\' \'lan\'
        option \'expandhosts\' \'1\'
        option \'nonegcache\' \'0\'
        option \'authoritative\' \'1\'
        option \'readethers\' \'1\'
        option \'leasefile\' \'/tmp/dhcp.leases\'
        option \'resolvfile\' \'/tmp/resolv.conf.auto\'

config \'dhcp\' \'lan\'
        option \'interface\' \'lan\'
        option \'leasetime\' \'12h\'
        option \'start\' \'' . ($max[3] + 2) . '\'
        option \'limit\' \'' . $limit . '\'
';
    _outln_comment();
    _outln_comment();
    _outln_comment(t('File /etc/config/dhcp'));
    _out_file($file_dhcp, '/etc/config/dhcp');
}
 function guifi_unsolclic_dhcp($dev)
 {
     $dhcp_statics = array();
     $max = explode(".", $dev->ipv4);
     function merge_static($link, &$dhcp_statics, &$max, &$curr)
     {
         if (empty($link['interface'][mac])) {
             $link['interface'][mac] = 'FF:FF:FF:FF:FF:FF';
         }
         $dhcp_statics[] = array($link['interface'][ipv4][ipv4], $link['interface'][mac], guifi_get_hostname($link['interface'][device_id]));
         $curr = explode(".", $link['interface'][ipv4][ipv4]);
         if ($curr[3] > $max[3]) {
             $max[3] = $curr[3];
         }
     }
     $main_ip = guifi_main_ip($dev->id);
     $item = _ipcalc_by_netbits($main_ip[ipv4], $main_ip[maskbits]);
     $max = explode(".", $main_ip[ipv4]);
     // cable links
     if (!empty($dev->interfaces)) {
         foreach ($dev->interfaces as $interface) {
             if (!empty($interface[ipv4])) {
                 foreach ($interface[ipv4] as $ipv4) {
                     if (!empty($ipv4[links])) {
                         foreach ($ipv4[links] as $link) {
                             if ($link['interface'][ipv4][ipv4] != '') {
                                 $item2 = _ipcalc($link['interface'][ipv4][ipv4], $link['interface'][ipv4][netmask]);
                                 if ($item[netid] == $item2[netid]) {
                                     merge_static($link, $dhcp_statics, $max, $cur);
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     // ap/client links
     if (!empty($dev->radios)) {
         foreach ($dev->radios as $radio) {
             if (!empty($radio[interfaces])) {
                 foreach ($radio[interfaces] as $interface) {
                     if (!empty($interface[ipv4])) {
                         foreach ($interface[ipv4] as $ipv4) {
                             if (!empty($ipv4[links])) {
                                 foreach ($ipv4[links] as $link) {
                                     if ($link['link_type'] == 'ap/client' and !empty($link['interface'][ipv4][ipv4])) {
                                         merge_static($link, $dhcp_statics, $max, $cur);
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     $statics = count($dhcp_statics) - 1;
     $totalstatics = count($dhcp_statics);
     if ($statics == -1) {
         _outln_comment();
         _outln_comment('DHCP');
         _outln_nvram('dhcp_start', $max[3] + 5);
         return;
     }
     _outln_comment();
     _outln_comment('DHCP');
     if ($dev->variable['firmware'] == 'Alchemy') {
         _out_nvram('dhcpd_statics');
         for ($i = 0; $i < $statics; $i++) {
             _out(implode(" ", $dhcp_statics[$i]));
         }
         _out(implode(" ", $dhcp_statics[$statics]), '"');
     }
     if ($dev->variable['firmware'] == 'DD-WRTv23' or $dev->variable['firmware'] == 'DD-guifi') {
         $staticText = "";
         foreach ($dhcp_statics as $static) {
             $staticText .= $static[1] . "=" . $static[2] . "=" . $static[0] . " ";
         }
         _out('nvram set static_leases="' . $staticText, ' "');
         _outln_nvram('static_leasenum', $totalstatics);
     }
     if ($dev->variable['firmware'] == 'Talisman') {
         _out_nvram('dhcp_statics');
         foreach ($dhcp_statics as $static) {
             _out($static[1] . "-" . $static[0] . "-" . $static[2] . " ");
         }
         _out(null, '"');
     }
     _outln_nvram('dhcp_start', $max[3] + 5);
     return;
 }