#!/bin/bash

set -e

ssl_dir="/usr/share/yunohost/yunohost-config/ssl/yunoCA"

do_init_regen() {
  if [[ $EUID -ne 0 ]]; then
    echo "You must be root to run this script" 1>&2
    exit 1
  fi

  # create certs and SSL directories
  mkdir -p "/etc/yunohost/certs/yunohost.org"
  mkdir -p "${ssl_dir}/"{ca,certs,crl,newcerts}

  # initialize some files
  [[ -f "${ssl_dir}/serial" ]] \
    || echo "00" > "${ssl_dir}/serial"
  [[ -f "${ssl_dir}/index.txt" ]] \
    || touch "${ssl_dir}/index.txt"

  openssl_conf="/usr/share/yunohost/templates/ssl/openssl.cnf"

  # create default certificates
  if [[ ! -f /etc/yunohost/certs/yunohost.org/ca.pem ]]; then
      openssl req -x509 -new -config "$openssl_conf" \
        -days 3650 -out "${ssl_dir}/ca/cacert.pem" \
        -keyout "${ssl_dir}/ca/cakey.pem" -nodes -batch 2>&1
      cp "${ssl_dir}/ca/cacert.pem" \
        /etc/yunohost/certs/yunohost.org/ca.pem
      ln -sf /etc/yunohost/certs/yunohost.org/ca.pem \
        /etc/ssl/certs/ca-yunohost_crt.pem
      update-ca-certificates
  fi

  if [[ ! -f /etc/yunohost/certs/yunohost.org/crt.pem ]]; then
      openssl req -new -config "$openssl_conf" \
        -days 730 -out "${ssl_dir}/certs/yunohost_csr.pem" \
        -keyout "${ssl_dir}/certs/yunohost_key.pem" -nodes -batch 2>&1
      openssl ca -config "$openssl_conf" \
        -days 730 -in "${ssl_dir}/certs/yunohost_csr.pem" \
        -out "${ssl_dir}/certs/yunohost_crt.pem" -batch 2>&1

      last_cert=$(ls $ssl_dir/newcerts/*.pem | sort -V | tail -n 1)
      chmod 640 "${ssl_dir}/certs/yunohost_key.pem"
      chmod 640 "$last_cert"

      cp "${ssl_dir}/certs/yunohost_key.pem" \
        /etc/yunohost/certs/yunohost.org/key.pem
      cp "$last_cert" \
        /etc/yunohost/certs/yunohost.org/crt.pem
      ln -sf /etc/yunohost/certs/yunohost.org/crt.pem \
        /etc/ssl/certs/yunohost_crt.pem
      ln -sf /etc/yunohost/certs/yunohost.org/key.pem \
        /etc/ssl/private/yunohost_key.pem
  fi
}

do_pre_regen() {
  pending_dir=$1

  cd /usr/share/yunohost/templates/ssl

  install -D -m 644 openssl.cnf "${pending_dir}/${ssl_dir}/openssl.cnf"
}

do_post_regen() {
  regen_conf_files=$1

  # Ensure that index.txt exists
  index_txt=/usr/share/yunohost/yunohost-config/ssl/yunoCA/index.txt
  [[ -f "${index_txt}" ]] || {
    if [[ -f "${index_txt}.saved" ]]; then
      # use saved database from 2.2
      sudo cp "${index_txt}.saved" "${index_txt}"
    elif [[ -f "${index_txt}.old" ]]; then
      # ... or use the state-1 database
      sudo cp "${index_txt}.old" "${index_txt}"
    else
      # ... or create an empty one
      sudo touch "${index_txt}"
    fi
  }

  # TODO: regenerate certificates if conf changed?
}

FORCE=${2:-0}
DRY_RUN=${3:-0}

case "$1" in
  pre)
    do_pre_regen $4
    ;;
  post)
    do_post_regen $4
    ;;
  init)
    do_init_regen
    ;;
  *)
    echo "hook called with unknown argument \`$1'" >&2
    exit 1
    ;;
esac

exit 0