1.1.1Updated a month ago
import { execSync } from "node:child_process";
import { HOST, HOST_URL, TOKEN } from "./config.ts";

const VerifyToken = async (token: string) => {
  return (await fetch(`${HOST_URL}/ping`, {
    method: 'POST',
    headers: new Headers({
      "Authorization": `Bearer ${token}`
    })
  })).ok;
}

let confirmation: boolean;

if(TOKEN) {
  const valid = await VerifyToken(TOKEN);

  if(valid) {
    execSync(`deno run -A -r -q ${HOST_URL}`);

    console.log(`Viapak initialized and updated. Please run the same command again.`);
    console.log();
    Deno.exit();
  }

  confirmation = confirm('Install a token now?');
} else {
  console.log();
  console.log(`You do not have a valid token configured to use Viapak.`);
  console.log();
  confirmation = confirm('Install a token now?');
}


if(!confirmation) Deno.exit(0);

let token: string | undefined;
let token_verified = false;

do {
  token = prompt('Please paste your access token:')?.trim() ?? '';

  if(!token) {
    console.log();
    console.log("No token was entered. Please try again, or enter 'exit' to quit.");
    continue;
  }

  if(['exit', 'quit'].includes(token.toLowerCase())) {
    console.log();
    Deno.exit(0);
  }

  token_verified = await VerifyToken(token);

  if(!token_verified) {
    console.log();
    console.log("The entered token was not valid. Please try again, or enter 'exit' to quit.");
  }
} while(!token_verified);

console.log();
console.log('Your token has been verified.');

switch(Deno.build.os) {
  case 'linux': {
    execSync(`echo '\nexport DENO_AUTH_TOKENS=${token.replace(/'/g, '\\\'')}@${HOST}\n' >> ~/.bashrc`);
    console.log();
    console.log("Your token should now be installed.");
    console.log(">>> Please run `source ~/.bashrc`");
    break
  }
  case 'windows': {
    execSync(`setx DENO_AUTH_TOKENS "${token}@${HOST}"`);
    console.log();
    console.log("Your token should now be installed.")
    console.log(">>> Please restart your terminal window or application.");
    break
  }

  case 'darwin': {
    execSync(`export DENO_AUTH_TOKENS=${token}@${HOST}`);
    console.log();
    console.log("Your token should now be installed.");
    console.log(">>> Please run `source ~/.bashrc`");
    break
  }
}

console.log();
console.log("If it did not work, please add the following configuration to your environment:");
console.log(`DENO_AUTH_TOKENS="${token}@${HOST}"`);
console.log();

Deno.exit(0);