#!/usr/local/bin/php
<?php

require_once("config.inc");
require_once("util.inc");
require_once("pfsense-utils.inc");

if (!isset($config['aliases']['alias'])) {
    // No aliases
    exit;
}

// Gather list of urltable / geoip aliases
$todo = array();
foreach ($config['aliases']['alias'] as $alias) {
    if (preg_match('/urltable/i', $alias['type'])) {
        $todo[] = $alias;
    } elseif ($alias['type'] == 'geoip') {
        $todo[] = $alias;
    }
}

if (count($todo) > 0) {
    log_error("{$argv[0]}: Starting up.");

    if ($argv[1] != "now") {
        // Wait a little before updating.
        $wait = mt_rand(5, 60);
        log_error("{$argv[0]}: Sleeping for {$wait} seconds.");
        sleep($wait);
    }

    log_error("{$argv[0]}: Starting URL table alias updates");

    $filter_reload = false;
    foreach ($todo as $alias) {
        if (preg_match('/urltable/i', $alias['type'])) {
            log_error("{$argv[0]}: start update {$alias['name']} ");
            $r = process_alias_urltable($alias['name'], $alias['url'], $alias['updatefreq']);
            if ($r == 1) {
                if ($alias['type'] == "urltable") {
                    exec("/sbin/pfctl -t " . escapeshellarg($alias['name']) . " -T replace -f /var/db/aliastables/" . escapeshellarg($alias['name']) . ".txt 2>&1", $result);
                    log_error("{$argv[0]}: Updated {$alias['name']} content from {$alias['url']}: ". $result[count($result)-1]);
                } else {
                    $filter_reload = true;
                }
            } elseif ($r == -1) {
                log_error("{$argv[0]}: {$alias['name']} does not need updating.");
            } else {
                log_error("{$argv[0]}: ERROR: could not update {$alias['name']} content from {$alias['url']}");
            }
        } elseif ($alias['type'] == 'geoip') {
            download_alias_geoip($alias);
            // load alias content
            exec("/sbin/pfctl -t " . escapeshellarg($alias['name']) . " -T replace -f /var/db/aliastables/" . escapeshellarg($alias['name']) . ".txt 2>&1", $result);
            log_error("{$argv[0]}: Updated {$alias['name']} content from geoip database: ". $result[count($result)-1]);
        }
    }

    if ($filter_reload) {
        configd_run("filter reload");
    }
}
