<?php

namespace App\Helpers\Utility;

use Symfony\Component\Process\Process;
use Illuminate\Support\Facades\Log;

class bgpq4 {
  
  /**
   * Return a list of cidr's split into ip and width
   */
  static function get_asn_cidr($_asn, $_v6 = false, $_crush = true) {
    if(filter_var($_asn)) {
      // Get the list of prefixes from bgpq4
      $bgpq4_process = new Process(['bgpq4', $_v6 ? '-6' : '-4', "-F", "%n/%l\n", "as$_asn"]);
      $bgpq4_process->run();

      if($bgpq4_process->isSuccessful()) {
        $final_process_output = $bgpq4_process->getOutput();

        if($_crush) {
          $crusher_process = new Process(['python3', './app/Bin/SubnetCrusher.py']);
          $crusher_process->setInput($bgpq4_process->getOutput());
          $crusher_process->run();
          
          if($crusher_process->isSuccessful()) {
            $final_process_output = $crusher_process->getOutput();
          }
          else {
            $final_process_output = null;
          }
        }

        if($final_process_output !== null) {
          $prefixes = [];
          preg_match_all('/((?:(?:(?:[A-Fa-f0-9]{1,4}:{1,2}){0,7}(?:[A-Fa-f0-9]{1,4}))|(?:(?:\d{1,3}\.?)){4})\-\d{1,3})/', str_replace('/', '-', $final_process_output), $prefixes);
            
          $return = [];

          foreach($prefixes[0] as $prefix) {
              $temp = explode('-', $prefix);
              $return[] = ['ip' => $temp[0], 'width' => $temp[1], 'full' => $temp[0] . '/' . $temp[1]];
          }

          return $return;
        }
      }

      return false;
    }
  }
}

?>