// Change this variable if another host is used for CAPIF
const CAPIF_HOSTNAME = 'capifcore';

const express = require('express'),
  app = express(),
  fs = require('fs'),
  shell = require('shelljs'),


  folderPath = './Responses/',
  bodyParser = require('body-parser'),
  path = require('path');

const { exec } = require('child_process');

// Create the folder path in case it doesn't exist
shell.mkdir('-p', folderPath);

 // Change the limits according to your response size
app.use(bodyParser.json({limit: '50mb', extended: true}));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true })); 
var opensslCommand = ''

if (CAPIF_HOSTNAME.includes(':')){
  opensslCommand = `openssl s_client -connect ${CAPIF_HOSTNAME} | openssl x509 -text > ./Responses/cert_server.pem`;
}
else{
  opensslCommand = `openssl s_client -connect ${CAPIF_HOSTNAME}:443 | openssl x509 -text > ./Responses/cert_server.pem`;
}

exec(opensslCommand, (error, stdout, stderr) => {
  if (error) {
    console.error(`Error generating CSR: ${stderr}`);
  }
});

fs.writeFileSync('./Responses/client_cert.crt', '');
fs.writeFileSync('./Responses/client_key.key', '');

app.get('/', (req, res) => res.send('Hello, I write data to file. Send them requests!'));

app.post('/generate_csr', (req, res) => {

  console.log(req.body);
  const csrFilePath = 'Responses/'+req.body.apiProvFuncRole+'_csr.pem';
  const privateKeyFilePath = 'Responses/'+req.body.apiProvFuncRole+'_key.key';

  const subjectInfo = {
    country: 'ES',
    state: 'Madrid',
    locality: 'Madrid',
    organization: 'Telefonica I+D',
    organizationalUnit: 'IT Department',
    emailAddress: 'admin@example.com',
  };

  const opensslCommand = `openssl req -newkey rsa:2048 -nodes -keyout ${privateKeyFilePath} -out ${csrFilePath} -subj "/C=${subjectInfo.country}/ST=${subjectInfo.state}/L=${subjectInfo.locality}/O=${subjectInfo.organization}/OU=${subjectInfo.organizationalUnit}/emailAddress=${subjectInfo.emailAddress}"`;

  exec(opensslCommand, (error, stdout, stderr) => {
    if (error) {
      console.error(`Error generating CSR: ${stderr}`);
    } else {
      console.log('CSR generated successfully:');
      fs.readFile(csrFilePath, 'utf8', (readError, csrContent) => {
        if (readError) {
          console.error(`Error reading CSR: ${readError}`);
          res.status(500).send('Error reading CSR');
        } else {
          console.log('CSR read successfully:');
          // Send the CSR content in the response
          fs.readFile(privateKeyFilePath, 'utf8', (readError, keyContent) => {
            if (readError) {
              console.error(`Error reading KEY: ${readError}`);
              res.status(500).send('Error reading KEY');
            } else {
              console.log('KEY read successfully:');
              // Send the CSR content in the response
              fs.unlink(csrFilePath, (err) => {
                if (err) {
                  console.error(`Error deleting file: ${err.message}`);
                } 
              });
              fs.unlink(privateKeyFilePath, (err) => {
                if (err) {
                  console.error(`Error deleting file: ${err.message}`);
                } 
              });
              res.send({csr: csrContent, key: keyContent});
            }
          });
        }
      });
    }
  });
});

app.post('/generate_csr_invoker', (req, res) => {

  console.log(req.body);
  const csrFilePath = 'Responses/invoker_csr.pem';
  const privateKeyFilePath = 'Responses/invoker_key.key';

  const subjectInfo = {
    country: 'ES',
    state: 'Madrid',
    locality: 'Madrid',
    organization: 'Telefonica I+D',
    organizationalUnit: 'IT Department',
    emailAddress: 'admin@example.com',
  };

  const opensslCommand = `openssl req -newkey rsa:2048 -nodes -keyout ${privateKeyFilePath} -out ${csrFilePath} -subj "/C=${subjectInfo.country}/ST=${subjectInfo.state}/L=${subjectInfo.locality}/O=${subjectInfo.organization}/OU=${subjectInfo.organizationalUnit}/emailAddress=${subjectInfo.emailAddress}"`;

  exec(opensslCommand, (error, stdout, stderr) => {
    if (error) {
      console.error(`Error generating CSR: ${stderr}`);
    } else {
      console.log('CSR generated successfully:');
      fs.readFile(csrFilePath, 'utf8', (readError, csrContent) => {
        if (readError) {
          console.error(`Error reading CSR: ${readError}`);
          res.status(500).send('Error reading CSR');
        } else {
          console.log('CSR read successfuly:');
          // Send the CSR content in the response
          fs.readFile(privateKeyFilePath, 'utf8', (readError, keyContent) => {
            if (readError) {
              console.error(`Error reading KEY: ${readError}`);
              res.status(500).send('Error reading KEY');
            } else {
              console.log('KEY read successfully:');
              // Send the CSR content in the response
              fs.unlink(csrFilePath, (err) => {
                if (err) {
                  console.error(`Error deleting file: ${err.message}`);
                } 
              });
              fs.unlink(privateKeyFilePath, (err) => {
                if (err) {
                  console.error(`Error deleting file: ${err.message}`);
                } 
              });
              res.send({csr: csrContent, key: keyContent});
            }
          });
        }
      });
    }
  });
});


app.post('/write_cert', (req, res) => {
  let extension = 'crt',
    fsMode = 'writeFile',
    filename = "client_cert",
    filePath = `${path.join(folderPath, filename)}.${extension}`,
    options = {encoding: 'binary'};
  fs[fsMode](filePath, req.body.cert, options, (err) => {
    if (err) {
      console.log(err);
      res.send('Error');
    }
  });
  extension = 'key';
  filename = "client_key";
  filePath = `${path.join(folderPath, filename)}.${extension}`;
  fs[fsMode](filePath, req.body.key, options, (err) => {
    if (err) {
      console.log(err);
      res.send('Error');
    }
    else {
      res.send('Success');
    }
  });
});

app.post('/write_ca', (req, res) => {
  let extension = 'pem',
    fsMode = 'writeFile',
    filename = "ca_cert",
    filePath = `${path.join(folderPath, filename)}.${extension}`,
    options = {encoding: 'binary'};
  fs[fsMode](filePath, req.body.ca_root, options, (err) => {
    if (err) {
      console.log(err);
      res.send('Error');
    }
    else {
      res.send('Success');
    }
  });
});

app.listen(3000, () => {
  console.log('ResponsesToFile App is listening now! Send them requests my way!');
  console.log(`Data is being stored at location: ${path.join(process.cwd(), folderPath)}`);
});