<?php

namespace App\Helpers\Utility;

use Symfony\Component\Process\Process;

class WhoIs {
  
  /**
   * Returns a list of emails for a given ASN that may be associated with it.
   */
  static function asn_emails($_asn) {
    if(preg_match('/(?:ASN|AS)*(\d+)?/i', $_asn)) {
      $command = new Process(['whois', "$_asn"]);

      $command->run();

      if($command->isSuccessful()) {
        $emails = [];

        $output = $command->getOutput();

        preg_match_all('/(\w+@\w+(?:\.\w+)+)/m', $output, $emails);

        return array_unique($emails[1]);
      }
    }

    return false;
  }

  static function location_lookup($_ip) {
    $command = new Process(['whois', '-a', $_ip]);

    $command->run();

    if($command->isSuccessful()) {
      $country = null;

      $output = $command->getOutput();

      if(str_contains($output, 'No no entries found')) {
        return 'NO_ENTRY';
      }
    
      preg_match_all('/(?:country:\s+)([A-z]+)/', $output, $country);


      return isset($country[1]) ? $country[1] : 'NO_COUNTRY';
    }

    return 'NO_COUNTRY';
  }

  static function ip_asn($_ip) {
    $command = new Process(['python3', './app/Bin/IpAsnLookup.py']);
    $command->setInput($_ip);
    $command->run();

    if($command->isSuccessful()) {
      $asns = [];

      return trim($command->getOutput());
    }
  }

}

?>