import fs from 'fs';
import path, { dirname, join } from 'path';
import { fileURLToPath } from 'url';

import configArgs from '../src/config/args';

const __dirname = dirname(fileURLToPath(import.meta.url));
const moduleDir = path.resolve(__dirname, '..');
const dockerFile = path.resolve(__dirname, '..', 'Dockerfile');

let content = `## This Dockerfile is auto-generated by scripts/buildDockerfile.ts

FROM node:24-alpine as builder

RUN apk update && apk upgrade

WORKDIR /app-build
COPY .dev.mk .
COPY bin ./bin
COPY package.json .
COPY package-lock.json .
COPY rollup.config.mjs .
COPY tsconfig.json .
COPY scripts ./scripts
COPY src ./src
COPY static ./static
RUN npm ci && NODE_ENV=production node_modules/.bin/rollup -c && npm pack && mv *.tgz /tmp/app.tgz

WORKDIR /app
RUN npm install --no-package-lock /tmp/app.tgz && rm -f /tmp/app.tgz && rm -rf /app-build && npm cache clean --force

ENV NODE_ENV=production`;

for (const [arg, env, def, type] of configArgs) {
  if (env === 'DM_PLUGINS') {
    content += ` \\\n ${env}=core/static,core/helloworld`;
  } else if (type === 'array') {
    content += ` \\\n ${env}=${(def as string[]).join(',')}`;
  } else if (type === 'boolean') {
    const boolDef = def ? 'true' : 'false';
    content += ` \\\n ${env}=${boolDef}`;
  } else if (type === 'json') {
    const jsonDef = JSON.stringify(def)
      .replace(/\\/g, '\\\\')
      .replace(/"/g, '\\"');
    content += ` \\\n ${env}="${jsonDef}"`;
  } else {
    const envDef = ((typeof def !== 'string' ? def.toString() : def) as string)
      .replace(/\\/g, '\\\\')
      .replace(/"/g, '\\"')
      .replace(new RegExp(moduleDir, 'g'), '/app/node_modules/ldap-rest');
    content += envDef.length > 0 ? ` \\\n ${env}="${envDef}"` : ` \\\n ${env}=`;
  }
}

content += `

USER node

EXPOSE 8081
CMD ["npx", "ldap-rest"]
`;

fs.writeFileSync(dockerFile, content);
