<?php

namespace App\Modules\Network\Commands;

use Log;

class GroupFastBgp extends \App\Console\Commands\BaseCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'group:fast-bgp';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Sorts prefixes based on supernetting and subnetting.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $start = microtime(true);

        $pipe = [
            0 => popen("php /var/www/html/creatia/artisan prefix:import", 'w'),
            1 => popen("php /var/www/html/creatia/artisan asn:import", 'w')
        ];
            
        pclose($pipe[0]);
        pclose($pipe[1]);

        // These two quickly swap prefixes across ASNs and associate new prefixes with ASNs
        \Artisan::call('prefix:associate');
        \Artisan::call('asn:reconcile');

        // The following two tasks can execute simultaneously...
        $pipe = [
            0 => popen("php /var/www/html/creatia/artisan prefix:announce", 'w'),
            1 => popen("php /var/www/html/creatia/artisan prefix:communities --thread-pool=4", 'w')
        ];
            
        pclose($pipe[0]);
        pclose($pipe[1]);

        // This must wait for everything else as communities are required to setup Mercury correctly...
        $pipe = [
            0 => popen("php /var/www/html/creatia/artisan goliath:setup", 'w'),
            1 => popen("php /var/www/html/creatia/artisan geoip:setup", 'w')
        ];
            
        pclose($pipe[0]);
        pclose($pipe[1]);

        \Artisan::call('prefix:delete');

        \Log::debug("Fast BGP execution: " . (microtime(true) - $start));
    
        return 0;
    }
}