process.env.HOME = "/tmp";

const { delay, handleTargetCreated, handleTargetDestroyed, logMainInfo, logMainError } = require("./utils");
const puppeteer = require("puppeteer");

const challengeUrl = process.env.CHALLENGE_HOST;

if (!challengeUrl) {
	logMainError("CHALLENGE_HOST environment variable is not set.");
	process.exit(1);
}

const tips = [
  "Every console.log usage on the bot will be sent back to you :)",
];
console.log(
  `Enter a URL starting with '${challengeUrl}' for the bot to visit.\n` +
	`Tips:\n- ${tips.join("\n- ")}\n`,
);

async function goto(url) {
  logMainInfo("Starting the browser...");
  const browser = await puppeteer.launch({
    headless: "new",
    ignoreHTTPSErrors: true,
    args: ["--no-sandbox", "--disable-gpu", "--disable-jit", "--disable-wasm", "--disable-dev-shm-usage"],
    executablePath: "/usr/bin/chromium-browser",
  });

  browser.on("targetcreated", handleTargetCreated.bind(browser));
  browser.on("targetdestroyed", handleTargetDestroyed.bind(browser));

  const [page] = await browser.pages();
  await handleTargetCreated(page.target());
  await page.setDefaultNavigationTimeout(5000);

  logMainInfo("Setting the secret cookie...");
  await page.setCookie({
    name: 'flag_auth',
    value: process.env.COOKIE_SECRET || 'super_secret_cookie_value_change_me',
    domain:  new URL(challengeUrl).hostname,
    path: '/',
    httpOnly: true,
    secure: false,
    sameSite: 'Strict',
  });

  logMainInfo("The bot is visiting the main page...");
  await page.goto(challengeUrl);

  logMainInfo("Going to the user provided link...");
  try {
    await page.goto(url);
  } catch {}
  await delay(3000);

  logMainInfo("Leaving o/");
  await browser.close();
  return;
}

process.stdin.on("data", (data) => {
  const url = data.toString().trim();

  if (!url || !url.startsWith(challengeUrl)) {
    logMainError(`You provided an invalid URL. It should start with '${challengeUrl}'.`);
    process.exit(1);
  }

  goto(url)
    .then(() => process.exit(0))
    .catch((error) => {
      if (process.env.ENVIRONMENT === "development") {
        console.error(error);
      }
      process.exit(1);
    });
});
