#!/bin/sh

CONFIG_FILE="/etc/stunnel/stunnel.conf"
KEY_FILE="/etc/stunnel/psk.txt"

adjust_config() {
  # Check if the [nfs] section exists in the config file
  if [ ! -f "$CONFIG_FILE" ] || ! grep -q "\[nfs\]" "$CONFIG_FILE"; then
    # If not, decode the base64 config and write it to the config file
    echo "$stunnel_config" | base64 --decode > "$CONFIG_FILE"
    echo "Updated stunnel configuration."

    # Decode the base64 public key and write it to the key file
    echo "$stunnel_psk" | base64 --decode > "$KEY_FILE"
    chmod 600 "$KEY_FILE"
    echo "Updated stunnel public key and set permissions."
  else
    echo "[nfs] section found in configuration; no changes made."
  fi
}

start() {
  printf "Starting stunnel: "
  adjust_config
  start-stop-daemon -S -q -p /var/run/stunnel.pid --exec /usr/bin/stunnel
  [ $? = 0 ] && echo "OK" || echo "FAIL"
}

stop() {
  printf "Stopping stunnel: "
  start-stop-daemon -K -q -p /var/run/stunnel.pid
  [ $? = 0 ] && echo "OK" || echo "FAIL"
}

restart() {
  stop
  start
}

case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart|reload)
    restart
    ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
esac

exit $?
