/**
 * Cloud-init user data generator for Discourse instances.
 */

export interface DiscourseConfig {
	hostname: string;
	adminEmail: string;
	smtpHost?: string;
	smtpPort?: number;
	smtpUser?: string;
	smtpPassword?: string;
}

export function generateCloudInit(config: DiscourseConfig): string {
	const smtpHost = config.smtpHost || "mail.rmail.online";
	const smtpPort = config.smtpPort || 587;
	const smtpUser = config.smtpUser || `noreply@rforum.online`;
	const smtpPassword = config.smtpPassword || "";

	return `#!/bin/bash
set -e

# Swap
fallocate -l 2G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
echo '/swapfile none swap sw 0 0' >> /etc/fstab

# Install Docker
apt-get update
apt-get install -y git docker.io docker-compose
systemctl enable docker
systemctl start docker

# Clone Discourse
git clone https://github.com/discourse/discourse_docker.git /var/discourse
cd /var/discourse

# Write app.yml
cat > containers/app.yml << 'APPYML'
templates:
  - "templates/postgres.template.yml"
  - "templates/redis.template.yml"
  - "templates/web.template.yml"
  - "templates/web.ssl.template.yml"
  - "templates/web.letsencrypt.ssl.template.yml"

expose:
  - "80:80"
  - "443:443"

params:
  db_default_text_search_config: "pg_catalog.english"

env:
  LANG: en_US.UTF-8
  DISCOURSE_DEFAULT_LOCALE: en
  DISCOURSE_HOSTNAME: '${config.hostname}'
  DISCOURSE_DEVELOPER_EMAILS: '${config.adminEmail}'
  DISCOURSE_SMTP_ADDRESS: '${smtpHost}'
  DISCOURSE_SMTP_PORT: ${smtpPort}
  DISCOURSE_SMTP_USER_NAME: '${smtpUser}'
  DISCOURSE_SMTP_PASSWORD: '${smtpPassword}'
  DISCOURSE_SMTP_ENABLE_START_TLS: true
  LETSENCRYPT_ACCOUNT_EMAIL: '${config.adminEmail}'

volumes:
  - volume:
      host: /var/discourse/shared/standalone
      guest: /shared
  - volume:
      host: /var/discourse/shared/standalone/log/var-log
      guest: /var/log
APPYML

# Bootstrap and start
./launcher bootstrap app
./launcher start app
`;
}
