#!/bin/bash -eu

tmpfile=""

#
# Clean up after ourselves.
#
do_cleanup() {
  trap - EXIT

  if [ -n "$tmpfile" -a -f "$tmpfile" ] ; then
    rm "$tmpfile"
  fi
}

trap do_cleanup EXIT

if [ $# -eq 0 ]; then
  echo "usage: symbiosis-generate-dhparams [-v] <path to config dir> [user]"
  exit 127
fi

verbose=""

while getopts ":v" opt; do 
  case $opt in
    v)
      verbose="yes"
      ;;
  esac
done
# shift away the option if it was there
shift $((OPTIND-1))

#
# This script regenerates Diffie-Helman parameters and chowns to the specified user
#
fileName="$1"
dir=$(dirname "$fileName")

mkdir -m 750 -p "$dir"

length=2048
tmpfile=$(tempfile -m 0600 -d "$dir" -p .dh)

if [ ! -f "$tmpfile" ] ; then
  echo "temporary file '$tmpfile' doesn't exist, stopping."
  exit 1
fi

[ -n "$verbose" ] && echo "Generating $fileName..."

if [ -z "$verbose" ] ; then
  certtool --generate-dh-params --sec-param medium --outfile "$tmpfile" > /dev/null 2>&1
else
  certtool --generate-dh-params --sec-param medium --outfile "$tmpfile"
fi


mv "$tmpfile" "$fileName"

[[ $# < 2 ]] && exit 0
chown "$2.$2" "$fileName"
