import { join } from '@std/path';
import { deployScript, purgePath, uploadFile } from './bunny_api/main.ts';

if (import.meta.main) {
  console.log(`Attempting to upload index.html`);
  const localFilepath = join(import.meta.dirname ?? '', '../build/index.html');
  const indexContents = Deno.readFileSync(localFilepath);
  await uploadFile('index.html', indexContents);
  console.log(`Done!`);

  console.log(`Attempting to purge the cache for index.html`);
  await purgePath('index.html');
  console.log(`Done!`);

  for (const dirEntry of Deno.readDirSync(
    join(import.meta.dirname ?? '', '../build/bunny')
  )) {
    if (dirEntry.isFile && dirEntry.name.endsWith('.js')) {
      const scriptName = dirEntry.name.substring(0, dirEntry.name.length - 3);
      const decoder = new TextDecoder('utf-8');
      const contents = decoder.decode(
        Deno.readFileSync(
          join(import.meta.dirname ?? '', '../build/bunny', dirEntry.name)
        )
      );

      console.log(`Attempting to deploy script '${scriptName}'`);
      await deployScript(scriptName, contents);
      console.log(`Done!`);
    }
  }
}