import { logger } from '../logger.js';
import * as plugins from '../plugins.js';
import type { CloudlyServerManager } from './classes.servermanager.js';

export class CurlFresh {
  public optionsArg = {
    npmRegistry: 'https://registry.npmjs.org',
  };
  public scripts = {
    'setup.sh': `#!/bin/bash

# lets update the system and install curl
# might be installed already, but entrypoint could have been wget
apt-get update
apt-get install -y --force-yes curl

# Basic updating of the software lists
echo 'debconf debconf/frontend select Noninteractive' | debconf-set-selections
apt-get update
apt-get upgrade -y --force-yes
apt-get install -y --force-yes fail2ban curl git
curl -sL https://deb.nodesource.com/setup_18.x | bash

# Install docker
curl -sSL https://get.docker.com/ | sh

# Install default nodejs to run nodejs tools
apt-get install -y nodejs zsh
zsh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" "" --unattended
npm config set unsafe-perm true

# lets install pnpm
curl -fsSL https://get.pnpm.io/install.sh | sh -

# lets make sure we use the correct npm registry
bash -c "npm config set registry ${this.optionsArg.npmRegistry}"

# lets install spark
bash -c "pnpm install -g @serve.zone/spark"

# lets install the spark daemon
bash -c "spark installdaemon"

# TODO: start spark with jump code
`,
  };

  public serverManagerRef: CloudlyServerManager;
  public curlFreshRoute: plugins.typedserver.servertools.Route;
  public handler = new plugins.typedserver.servertools.Handler('ALL', async (req, res) => {
    logger.log('info', 'curlfresh handler called. a server might be coming online soon :)');
    const scriptname = req.params.scriptname;
    switch (scriptname) {
      case 'setup.sh':
        logger.log('info', 'sending setup.sh');
        res.type('application/x-sh');
        res.send(this.scripts['setup.sh']);
        break;
      default:
        res.send('no script found');
        break;
    }
  });

  constructor(serverManagerRefArg: CloudlyServerManager) {
    this.serverManagerRef = serverManagerRefArg;
  }
  public async getServerUserData(): Promise<string> {
    const sslMode =
      await this.serverManagerRef.cloudlyRef.config.appData.waitForAndGetKey('sslMode');
    let protocol: 'http' | 'https';
    if (sslMode === 'none') {
      protocol = 'http';
    } else {
      protocol = 'https';
    }

    const domain =
      await this.serverManagerRef.cloudlyRef.config.appData.waitForAndGetKey('publicUrl');
    const port =
      await this.serverManagerRef.cloudlyRef.config.appData.waitForAndGetKey('publicPort');

    const serverUserData = `#cloud-config
  runcmd:
    - curl -o- ${protocol}://${domain}:${port}/curlfresh/setup.sh | sh
  `;
    console.log(serverUserData);
    return serverUserData;
  }
}