#!/usr/bin/env node
<% tab = n => (usingTabs ? "\t" : "  ").repeat(n) -%>

<% if (typeModule) { -%>
import { spawn } from 'node:child_process'
<% if (options.swap  && !flySetup()) { -%>
import { writeFileSync } from 'node:fs'
<% } -%>
<% } else { -%>
const { spawn } = require('node:child_process')
<% if (options.swap && !flySetup()) { -%>
const { writeFileSync } = require('node:fs')
<% } -%>
<% } -%>

const env = { ...process.env }

<% if (adonisjs && postgres) { -%>
if (process.env.DATABASE_URL) {
<%= tab(1) %>try {
<%= tab(2) %>const databaseUrl = new URL(process.env.DATABASE_URL)
<%= tab(2) %>env.PG_HOST = databaseUrl.hostname
<%= tab(2) %>env.PG_PORT = databaseUrl.port
<%= tab(2) %>env.PG_USER = databaseUrl.username
<%= tab(2) %>env.PG_PASSWORD = databaseUrl.password
<%= tab(2) %>env.PG_DB_NAME = databaseUrl.pathname.slice(1)
<%= tab(1) %>} catch (err) {
<%= tab(2) %>console.error('Invalid DATABASE_URL')
<%= tab(1) %>}
}

<% } -%>
;(async() => {
<% if (options.swap && !flySetup()) { -%>
<%= tab(1) %>// allocate swap space
<%= tab(1) %>await exec('fallocate -l <%= options.swap %> /swapfile')
<%= tab(1) %>await exec('chmod 0600 /swapfile')
<%= tab(1) %>await exec('mkswap /swapfile')
<%= tab(1) %>writeFileSync('/proc/sys/vm/swappiness', '10')
<%= tab(1) %>await exec('swapon /swapfile')
<%= tab(1) %>writeFileSync('/proc/sys/vm/overcommit_memory', '1')

<% } -%>
<% if (prisma || (build && options.deferBuild)) { -%>
<%= tab(1) %>// If running the web server then migrate existing database
<%= tab(1) %>if (process.argv.slice(2).join(' ') === '<%= packager %> run start'<% if (litefs) { %> && process.env.FLY_REGION === process.env.PRIMARY_REGION<% } %>) {
<% if (prisma) { -%>
<%= tab(2) %>await exec('<%= npx %> prisma migrate deploy')
<% } -%>
<% if (build && options.deferBuild) { -%>
<%= tab(2) %>await exec('<%= packager %> run build')
<% } -%>
<%= tab(1) %>}

<% } -%>
<%= tab(1) %>// launch application
<%= tab(1) %>await exec(process.argv.slice(2).join(' '))
})()

<%= tab(0) %>function exec(command) {
<%= tab(1) %>const child = spawn(command, { shell: true, stdio: 'inherit', env })
<%= tab(1) %>return new Promise((resolve, reject) => {
<%= tab(2) %>child.on('exit', code => {
<%= tab(3) %>if (code === 0) {
<%= tab(4) %>resolve()
<%= tab(3) %>} else {
<%= tab(4) %>reject(new Error(`${command} failed rc=${code}`))
<%= tab(3) %>}
<%= tab(2) %>})
<%= tab(1) %>})
<%= tab(0) %>}
