#!/bin/sh

set -e

#
# Skip, if we are not in "configure" state
#
if [ "$1" != "configure" ]; then
        echo "I: Skipping configuration"
        exit 0
fi

if [ ! -f /etc/ssl/private/pure-ftpd-dhparams.pem ] ; then
  #
  # generate dhparams if they don't exist already
  #
  /etc/cron.weekly/symbiosis-ftpd --verbose
fi

#
#  Remove existing PAMAuthentication setup,
#
find /etc/pure-ftpd/auth/ -lname "*/PAMAuthentication"  -exec rm -f \{\} \;
find /etc/pure-ftpd/auth/ -lname "*/UnixAuthentication" -exec rm -f \{\} \;

#
# Edit our defaults to set it to "standalone"
#
if [ -f /etc/default/pure-ftpd-common ] ; then
  sed -i -e 's/^STANDALONE_OR_INETD=.*$/STANDALONE_OR_INETD=standalone/' /etc/default/pure-ftpd-common
fi

#
# Disable any inetd service
#
if [ -f /etc/inetd.conf -a -x /usr/sbin/update-inetd ] ; then
  update-inetd --disable ftp
  # Don't really care if this errors.
  invoke-rc.d  openbsd-inetd restart || true
fi

##
# SSL cert generation now in symbiosis-common
##

#
#  Link in the certificate if we have one.
#
if [ ! -e /etc/ssl/private/pure-ftpd.pem ]; then
    ln -s /etc/ssl/ssl.combined /etc/ssl/private/pure-ftpd.pem
fi

if [ -e /etc/ssl/private/pure-ftpd.pem ] ; then
  #
  #  TLS should be enabled if we did the linking.
  #
  echo '2' > /etc/pure-ftpd/conf/TLS

  #
  # Set the TLS cipher suites
  #
  cs="/etc/pure-ftpd/conf/TLSCipherSuite"
  if [ -f "$cs" ] && \
    ( echo "9939bfb21f5be996e89b8a9e43bab6ba  $cs" | md5sum -c > /dev/null 2>&1 || \
      echo "debef44fdd534db09718bd42c34d83af  $cs" | md5sum -c > /dev/null 2>&1 ) ; then

    # OK this is the Debian ciphers, or previously updated ones.
    echo "I: Updating pure-ftpd cipher suite"

    #
    # If this list changes, remember to change the md5 in the prerm too.
    #
    echo 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS' > $cs
  fi
fi

#DEBHELPER#

#
# Add symlinks for the monit script
# 
monit_dir="/etc/symbiosis/monit.d"
mkdir -p "$monit_dir"

for i in pure-ftpd; do
  monit_script="/usr/share/symbiosis/monit/checks/$i"
  link_target="$monit_dir/$i"

  if [ -x "$monit_script" ] && [ ! -e "$link_target" ]; then
    echo "I: Adding symlink for Symbiosis Monit script for $i"
    ln -s "$monit_script" "$link_target" || true
  fi
done

invoke-rc.d pure-ftpd restart

exit 0
