#!/usr/bin/env php
<?php
    if (!@include_once(getenv('FREEPBX_CONF') ? getenv('FREEPBX_CONF') : '/etc/freepbx.conf')) { 
        include_once('/etc/asterisk/freepbx.conf'); 
        $restrict_mods = array('firewall' => true);
    }

    $fw         = FreePBX::Firewall();
    $advanced   = $fw->getConfig("advancedsettings");
    $hosts      = file("/etc/hosts");
    $ipHosts    = [];
    foreach ($hosts as $h) {
        $line = preg_split("/\s+/", trim($h));
        if (empty($line[0])) {
            continue;
        }
        if (filter_var($line[0], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
            if(!empty($advanced["import_hosts"]) && ($advanced["import_hosts"] != "disabled" && $line[0] != "127.0.0.1")){
                $ipHosts[] = $line[0];
                $fw->setConfig("whiteHosts",implode("\n", $ipHosts));
            }
            else{
                $fw->setConfig("whiteHosts");
            }	
        }
    }

    $FC     = fc();
    /**
     * cmd line below, ready for Fail2ban 0.11.1 
     */
    $cmd    = "$FC status | grep 'Jail list' | sed -r 's/.+Jail list:\t+//g' | sed -e 's/ *//g' -e 's/\,/\\n/g'";
    exec($cmd, $out, $ret);
    if($ret === 0 && is_array($out)){
        foreach($out as $jail){
            exec("$FC get $jail ignoreip | grep - | cut -d' ' -f2 | uniq", $whiteips, $ret2);
            $whiteips   = array_merge($whiteips, $ipHosts);
            $whitelist  = implode("\n",array_unique($whiteips));
            $fw->setConfig("dynamic_whitelist",str_replace("/32","",$whitelist));
            break;      
        }
    }

    /**
     * Removing flag at the end of script.
     */
    @unlink($fw->get_astspooldir()."/tmp/getdyn.flg");
    exit();

    function fc(){
        return fpbx_which("fail2ban-client");
    }
?>
