import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";

import * as csv from "csv-parse";

import { exec } from "child_process";
import { getCloudASN } from "./getCloudASN.js";
import { generateWellKnownIPs } from "./wellKnown";

const __dirname = path.dirname(fileURLToPath(import.meta.url));

const getCloudASN = async () =>
  new Promise(async (resolve, reject) => {
    const results = [];
    const cloudList = (
      await fs.promises.readFile(path.join(__dirname, "./cloud_list.md"))
    )
      .toString()
      .split("\n");

    fs.createReadStream("./as.csv")
      .pipe(csv.parse({ delimiter: ",", from_line: 2 }))
      .on("data", function ([asn, handle, description]) {
        if (cloudList.includes(handle) || cloudList.includes(description)) {
          results.push({ asn, handle, description });
        }
      })
      .on("end", function () {
        resolve(results);
      })
      .on("error", function (error) {
        console.log(error.message);
        reject(error.message);
      });
  });

const buildIpRange = async () => {
  const dir = path.join(__dirname, "ip_ranges");
  if (!fs.existsSync(path.join(__dirname, "ip_ranges"))) {
    fs.mkdirSync(path.join(__dirname, "ip_ranges"));
  }
  const cloudASM = await getCloudASN();
  for (const { asn, handle } of cloudASM) {
    try {
      await new Promise((resolve, reject) => {
        exec(
          `bgpq3 -h whois.radb.net -j AS${asn} > ip_ranges/${handle}.json`,
          (error, stdout, stderr) => {
            if (error) {
              console.error(`exec error: ${error}`);
              reject(error);
              return;
            }
            resolve();
          }
        );
      });
    } catch (error) {
      console.error(`${asn}, ${handle} failed`);
    }
  }
  generateWellKnownIPs();
};

buildIpRange();
