#!/usr/bin/env bash

# Clear the distribution assets
rm -rf ../dist/*;

# Build the server application
cd ../server/;
rm -rf dist/*;
npm run build;
cp -r dist/* ../dist/;

# Copy prisma schema
cp src/prisma/schema.prisma ../dist/prisma/;

# Copy the PM2 scripts
cp staging.config.js ../dist/;
cp production.config.js ../dist/;

# Copy the servers package file as the dependencies
# need to be included during runtime
node -e "const { writeFileSync } = require('fs');
const { devDependencies, jest, ...restPkg } = require(process.cwd()+'/package.json');
const { 'start:prod': start_prod, 'start:staging': start_staging, ...restScripts } = restPkg.scripts;
restPkg.scripts = {};
restPkg.scripts['start:staging'] = 'todo';
restPkg.scripts['start:prod'] = 'todo';
restPkg.main = 'main.js';
restPkg.prisma.schema = './prisma/schema.prisma';
(async function () { await writeFileSync('../dist/package.json', JSON.stringify(restPkg, null, 2)); })();"

# Build the client application
cd ../client/;
npm run "build:staging";
cp -r .output/public/ ../dist/static;

#cd ../dist/
#npm install
#npx prisma generate