### BEGIN INIT INFO
# Provides:          certs-ramfs
# Required-Start:    $remote_fs $syslog $network cloud-config
# Required-Stop:     $remote_fs $syslog $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Creates an encrypted ramfs for Octavia certs
# Description:       Creates an encrypted ramfs for Octavia TLS
#                    certificates and key storage.
### END INIT INFO

# Using the lsb functions to perform the operations.
. /lib/lsb/init-functions
# Process name ( For display )
NAME=certs-ramfs

case $1 in
 start)
  log_daemon_msg "Starting the process" "$NAME"
  modprobe brd
  passphrase=$(head /dev/urandom | tr -dc "a-zA-Z0-9" | fold -w 32 | head -n 1)
  certs_path=$(awk "/base_cert_dir / {printf \$3}" /etc/octavia/amphora-agent.conf)
  mkdir -p "${certs_path}"
  echo -n "${passphrase}" | cryptsetup luksFormat /dev/ram0 -
  echo -n "${passphrase}" | cryptsetup luksOpen /dev/ram0 certfs-ramfs -
  mkfs.ext2 /dev/mapper/certfs-ramfs
  mount /dev/mapper/certfs-ramfs "${certs_path}"
  log_end_msg 0
  ;;
 stop)
  log_daemon_msg "Stopping the process" "$NAME"
  certs_path=$(awk "/base_cert_dir / {printf \$3}" /etc/octavia/amphora-agent.conf)
  umount "${certs_path}"
  cryptsetup luksClose /dev/mapper/certfs-ramfs
  log_end_msg 0
  ;;
 restart)
  # Restart the daemon.
  $0 stop && sleep 2 && $0 start
  ;;
 *)
  # For invalid arguments, print the usage message.
  echo "Usage: $0 {start|stop|restart|reload|status}"
  exit 2
  ;;
esac
