process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0;

const express = require('express');
const nodemailer = require("nodemailer");
const request = require('sync-request');
const randomstring = require("randomstring");
const validator = require('validator');

const app = express();
  let transporter = nodemailer.createTransport({
    host: "mail.email.radio",
    port: 587,
    secure: false, // true for 465, false for other ports
    auth: {
      user: process.env.SYSTEM_USERNAME, // generated ethereal user
      pass: process.env.SYSTEM_PASSWORD, // generated ethereal password
    },
  }); 

app.get('/signup', async (req, res) => {
  var { email, callsign } = req.query
  res.set("Access-Control-Allow-Origin", "*")
  if (!email) return res.json({ success: false, error: "Please provide an error" })
  if (!callsign) return res.json({ success: false, error: "Please provide a callsign" })
  if (!validator.isEmail(email)) return res.json({ success: false, error: "Please provide a (valid) email" })
  if (callsign.length > 7 || callsign.length < 3) return res.json({ success: false, error: "Please provide a (valid) callsign" })
  callsign = callsign.toLowerCase()
  var a = request('GET', 'https://mail.email.radio/api/v1/get/mailbox/all/email.radio', {
  headers: {
    'Content-Type': "application/json",
    'X-API-Key': process.env.MAILCOW_API_KEY,
  }}).getBody("utf8")
  var boxes = JSON.parse(a)
  if (boxes.find(box=>box.local_part == callsign.toLowerCase())) return res.json({ success: false, error: "There is already someone using this callsign. If someone is using your callsign, please email postmaster@email.radio" })
  await transporter.sendMail({
    from: process.env.SYSTEM_USERNAME, // sender address
    to: email, // list of receivers
    subject: "Signup recieved!", // Subject line
    text: `Thanks for signing up for email.radio!

Please note, this service is only for licensed amateur radio operators. You'll get a reply once we have verified that you are a licensed amateur radio operator.

(Not you? You can safely ignore this email.)
`, // plain text body
    html: `<h1>Thanks for signing up for email.radio!</h1>
<p>Please note, this service is only for licensed amateur radio operators. You'll get a reply once we have verified that you are a licensed amateur radio operator.</p>
<p><small>(Not you? You can safely ignore this email.)</small></p>`, // html body
  });
  await transporter.sendMail({
    from: process.env.SYSTEM_USERNAME, // sender address
    to: process.env.ADMIN_EMAIL, // list of receivers
    subject: "New application from "+callsign, // Subject line
    text: `New signup from ${callsign}!

${callsign} has signed up for ${callsign}@email.radio. The normal email is ${email}

Follow this link to approve: https://signup.email.radio/approve?email=${encodeURIComponent(email)}&callsign=${encodeURIComponent(callsign)}
`, // plain text body
    html: `<h1>New signup from ${callsign}!</h1>
<p>${callsign} has signed up for ${callsign}@email.radio. The normal email is ${email}</p>
<a target="_blank" href="https://signup.email.radio/approve?email=${encodeURIComponent(email)}&callsign=${encodeURIComponent(callsign)}">Click here to approve this user.</a>`, // html body
  });
  res.json({ success: true })
});
app.get('/approve', async (req, res) => {
  const { email, callsign } = req.query
  res.set("Access-Control-Allow-Origin", "*")
  const password = randomstring.generate(24);

  if (!email || !callsign) return res.json({ success: false })
  await transporter.sendMail({
    from: process.env.SYSTEM_USERNAME, // sender address
    to: email, // list of receivers
    subject: "Signup approved!", // Subject line
    text: `Thanks for signing up for email.radio!

We approved your application to email.radio! Please login using the following credentials:
Email: ${callsign}@email.radio
Password: ${password} (On 1st login, you'll be prompted to change your password)

IMAP:
Host: mail.email.radio
Port: 143
SSL: STARTTLS
Password: ${password}

SMTP:
Host: mail.email.radio
Port: 587
SSL: STARTTLS
Password: ${password}

User Dashboard: https://mail.email.radio
Online E-Mail Client: https://mail.email.radio/SOGo

(Not you? Please email admin@email.radio to have this issue solved!)
`, // plain text body
    html: `<h1>Thanks for signing up for email.radio!</h1>

<p>We approved your application to email.radio! Please login using the following credentials:</p>
<p>Email: ${callsign}@email.radio</p>
<p>Password: <code>${password}</code> (On 1st login, you'll be prompted to change your password)</p>

IMAP:
<p>Username: <code>${callsign}@email.radio</code></p>
<p>Host: <code>mail.email.radio</code></p>
<p>Port: <code>143</code></p>
<p>SSL: <code>STARTTLS</code></p>
<p>Password: <code>${password}</code></p>

SMTP:
<p>Username: <code>${callsign}@email.radio</code></p>
<p>Host: <code>mail.email.radio</code></p>
<p>Port: <code>587</code></p>
<p>SSL: <code>STARTTLS</code></p>
<p>Password: <code>${password}</code></p>

<p>User Dashboard: <a href="https://mail.email.radio" target="_blank">https://mail.email.radio</a></p>
<p>Online E-Mail Client: <a href="https://mail.email.radio/SOGo" target="_blank">https://mail.email.radio/SOGo</a></p>
<p><small>(Not you? Please email admin@email.radio to have this issue solved!)</small></p>    
    `, // html body
  });
var a = request('POST', 'https://mail.email.radio/api/v1/add/mailbox', {
  headers: {
    'Content-Type': "application/json",
    'X-API-Key': process.env.MAILCOW_API_KEY,
  },
    json: {
  force_pw_update: 1,
  sogo_access: ["0", "1"],
  protocol_access: ["0", "imap", "pop3", "smtp", "sieve"],
  local_part: callsign,
  domain: "email.radio",
  name: callsign,
  password: password,
  password2: password,
  tags: "",
  quota: 1024,
  quarantine_notification: "hourly",
  quarantine_category: "reject",
  acl: [
    "spam_alias",
    "tls_policy",
    "spam_score",
    "spam_policy",
    "delimiter_action",
    "eas_reset",
    "pushover",
    "quarantine",
    "quarantine_attachments",
    "quarantine_notification",
    "quarantine_category",
    "app_passwds",
  ],
  rl_value: "",
  rl_frame: "s",
  active: 1,
}});
  console.log(a.getBody('utf8'))
  res.send("Approval successful!")
})



app.listen(3000, () => {
  console.log('server started');
});