#!/usr/bin/env node

/**
 * Obtaining Amazon SES SMTP credentials by converting existing AWS credentials
 *
 * Script based on:
 * https://docs.aws.amazon.com/ses/latest/dg/smtp-credentials.html
 */

const crypto = require('crypto');

const SMTP_REGIONS = [
  'us-east-2', // US East (Ohio)
  'us-east-1', // US East (N. Virginia)
  'us-west-2', // US West (Oregon)
  'ap-south-1', // Asia Pacific (Mumbai)
  'ap-northeast-2', // Asia Pacific (Seoul)
  'ap-southeast-1', // Asia Pacific (Singapore)
  'ap-southeast-2', // Asia Pacific (Sydney)
  'ap-northeast-1', // Asia Pacific (Tokyo)
  'ca-central-1', // Canada (Central)
  'eu-central-1', // Europe (Frankfurt)
  'eu-west-1', // Europe (Ireland)
  'eu-west-2', // Europe (London)
  'sa-east-1', // South America (Sao Paulo)
  'us-gov-west-1', // AWS GovCloud (US)
];

// These values are required to calculate the signature. Do not change them.
const DATE = '11111111';
const SERVICE = 'ses';
const MESSAGE = 'SendRawEmail';
const TERMINAL = 'aws4_request';
const VERSION = [0x04];

function sign(key, msg) {
  return crypto.createHmac('sha256', key).update(msg).digest();
}

function calculate_key(secret_access_key, region) {
  if (!SMTP_REGIONS.includes(region)) {
    throw new Error(`The ${region} Region doesn't have an SMTP endpoint`);
  }

  let signature;

  signature = sign(`AWS4${secret_access_key}`, DATE);
  signature = sign(signature, region);
  signature = sign(signature, SERVICE);
  signature = sign(signature, TERMINAL);
  signature = sign(signature, MESSAGE);

  const signature_and_version = Buffer.concat([
    Buffer.from(VERSION),
    signature,
  ]);

  const smtp_password = Buffer.from(signature_and_version).toString('base64');

  return smtp_password;
}

function main() {
  const [secret, region] = process.argv.slice(2);

  console.log(calculate_key(secret, region));
}

if (require.main === module) {
  main();
}