<?php

namespace App\Console\Commands\Utility;

use Illuminate\Support\Facades\Redis;

class ListGoliath extends \App\Console\Commands\BaseCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'list:goliath {--region=} {--special=} {--type=} {--summary=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Pulls and displays a relevant goliath configuration as a pretty printed JSON output.';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {

        $region       = $this->option('region');
        $special      = $this->option('special');
        $type         = $this->option('type');
        $summary         = $this->option('summary');

        $label = ($type === 'flags' ? 'goliath-flags' : 'goliath-chains') . ($special === '0' ? '' : "-$special") . ($region === '0' ? '' : ".$region");

        $configuration = Redis::get($label);

        if($configuration !== null) {
            if($summary && $type === 'flags') {
                $count_h1 = substr_count($configuration, '"heuristicsLevel":1');
                $count_h2 = substr_count($configuration, '"heuristicsLevel":2');
                $count_h3 = substr_count($configuration, '"heuristicsLevel":3');
                $count_syn_on = substr_count($configuration, '"synproxy":true');
                $count_syn_off = substr_count($configuration, '"synproxy":false');
                $count_fivem_on = substr_count($configuration, '"fivem":true');
                $count_fivem_off = substr_count($configuration, '"fivem":false');
                $count_clamp_on = substr_count($configuration, '"clampMSS":true');
                $count_chain = substr_count($configuration, '"chainID":');
                $count_poe = substr_count($configuration, '"poe":');
                $count_silk = substr_count($configuration, '"silkroad":');

                echo "MITIGATION CONFIGURATION SUMMARY\n"
                    . "H1: $count_h1 \nH2: $count_h2 \nH3: $count_h3 \n"
                    . "SYN-ON: $count_syn_on\nSYN-OFF: $count_syn_off\n"
                    . "FIVEM-ON: $count_fivem_on\nFIVEM-OFF: $count_fivem_off\n" 
                    . "CLAMP-MSS: $count_clamp_on\n"
                    . "CHAIN: $count_chain\n"
                    . "SPECIAL-POE: $count_poe\n"
                    . "SPECIAL-SILKROAD: $count_silk\n";

            } else {
                echo json_encode(json_decode($configuration, true), JSON_PRETTY_PRINT);
            }

        } 
        else {
            echo "Invalid combination of parameters supplied - No configuration found.";
        }
    
        return 0;
    }
}