#!/bin/bash

set -eu

source ../utils/common.sh

input "Specify the output path:" OUTPUT_PATH

if [ -z "$OUTPUT_PATH" ]; then
  OUTPUT_PATH="$(pwd)/output"

  if [[ ! -e "$OUTPUT_PATH" ]]; then 
    mkdir "$OUTPUT_PATH"
  fi 
fi

if [[ ! -e "$OUTPUT_PATH" ]]; then 
  print_error "${OUTPUT_PATH} doesn't exist."
  exit;
fi

rm -rvf "$OUTPUT_PATH/*"

input "Do you have cfssl installed?(y/n): " is_cfssl_installed

CFSSLEXE=${OUTPUT_PATH}/cfssl
CFSSLJSONEXE=${OUTPUT_PATH}/cfssljson

if [[ "${is_cfssl_installed}" == "y" || "${is_cfssl_installed}" == "Y" ]]; then 
  input "Specify the path where the cfssl and cfssljson are placed: " TOOL_PATH

  CFSSLEXE=${TOOL_PATH}/cfssl
  CFSSLJSONEXE=${TOOL_PATH}/cfssljson

  print_highlight "Your cfssl binary path is ${CFSSLEXE}"

  if [ ! -e "$CFSSLEXE" ]; then
      print_error "no cfssl found."
      exit;
  fi

  if [ ! -e "$CFSSLJSONEXE" ]; then
      print_error "no cfssljson found."
      exit;
  fi

else
  # Download the cfssl for users
  input "Specify your platform(darwin/linux/windows): " PLATFORM  

  if [ -z "$PLATFORM" ]; then 
    print_error "Platform must be provided."
    exit;
  fi

  print_highlight "Only amd64 is supported"

  wget "https://github.com/cloudflare/cfssl/releases/download/v1.6.1/cfssl_1.6.1_${PLATFORM}_amd64" -O "${OUTPUT_PATH}/cfssl"
  chmod +x "${OUTPUT_PATH}/cfssl"
  wget "https://github.com/cloudflare/cfssl/releases/download/v1.6.1/cfssljson_1.6.1_${PLATFORM}_amd64" -O "${OUTPUT_PATH}/cfssljson"
  chmod +x "${OUTPUT_PATH}/cfssljson"

  print_highlight "Download the cfssl bundle successfully."
fi

cd $OUTPUT_PATH

input "Give a name to the CA certificate: " CA_CERT_NAME

CA_CERT_NAME=${CA_CERT_NAME}-ca

${CFSSLEXE} print-defaults csr | ${CFSSLEXE} gencert -initca - | ${CFSSLJSONEXE} -bare ${CA_CERT_NAME} 

CONFIG_CFSSL_JSON=${OUTPUT_PATH}/cfssl.json

cat <<EOF >> ${CONFIG_CFSSL_JSON}
{
  "signing": {
    "default": {
      "expiry": "87600h",
      "usages": ["signing", "key encipherment", "server auth"]
    }
  }
}
EOF

input "Give a name to the certificate: " CERT_NAME

input "Input the hostname(example.org,127.0.0.1): " CERT_HOSTNAME

echo '{}' | ${CFSSLEXE} gencert -ca=${CA_CERT_NAME}.pem -ca-key=${CA_CERT_NAME}-key.pem -config=${CONFIG_CFSSL_JSON} \
    -hostname="${CERT_HOSTNAME}" - | ${CFSSLJSONEXE} -bare ${CERT_NAME}

print_highlight "The custom TLS certificates are successfully generated in the path ${OUTPUT_PATH}."
