#!/bin/bash

set -x

ARGS=( "$@" )

getarg() { # by Univention
  local found=0
  for arg in "${ARGS[@]}"; do
    if [ "$found" -eq 1 ]; then
      echo "$arg"
      break
    fi
    if [ "$arg" = "$1" ]; then
      found=1
    fi
  done
}

echo "Setting Host Alias"
FQDN="$(ucr get hostname).$(ucr get domainname)"
ucr set appcenter/apps/filewave/docker/params="--add-host ${FQDN}:127.0.0.1"

if ! [[ -d "/fw/configs/certs" ]]; then
  mkdir -p "/fw/configs/certs"

  if [[ -f "/etc/univention/letsencrypt/signed_chain.crt" ]] && [[ -f "/etc/univention/letsencrypt/domain.key" ]]; then
    echo "Copying LE certs"
    cp /etc/univention/letsencrypt/signed_chain.crt /fw/configs/certs/server.crt
    cp /etc/univention/letsencrypt/domain.key /fw/configs/certs/server.key
  else
    echo "Copying default UCS certs"
    cp /etc/univention/ssl/${FQDN}/cert.pem /fw/configs/certs/server.crt
    cp /etc/univention/ssl/${FQDN}/private.key /fw/configs/certs/server.key
  fi

  chmod 664 /fw/configs/certs/server.crt
  chmod 600 /fw/configs/certs/server.key
  chown 1000:1000 /fw/configs/certs/server.key /fw/configs/certs/server.crt
fi

echo "Configuring web admin port"
if ! [[ -d "/fw/configs/apache" ]]; then
  mkdir -p "/fw/configs/apache"
fi
touch /fw/configs/apache/httpd_webadmin.conf

if ! grep -q 'Define WEB_ADMIN_PORT 4443' /fw/configs/apache/httpd_webadmin.conf; then
  echo 'Define WEB_ADMIN_PORT 4443' > /fw/configs/apache/httpd_webadmin.conf
fi

# Upgrade
old_version="$(getarg "--old-version")"
if [[ -n "${old_version}" ]]; then

  echo "Upgrade requested. Pulling new installer and running installation first."

  new_version="$(getarg "--version")"

  if [[ -z "${new_version}" ]]; then
    echo "New version not detected"
    exit 1
  fi

  installer="https://fwdl.filewave.com/${new_version}/fwxserver_${new_version}_amd64.deb"

  if ! univention-app shell filewave fwxserver -V | grep -q "${new_version}"; then
    if ! univention-app shell filewave curl -fLo /install/fwxserver.deb "${installer}"; then
      echo "Failed to pull installer from ${installer}."
      exit 1
    fi
    if ! univention-app shell filewave apt install -y --reinstall /install/fwxserver.deb; then
      echo "Failed to install ${new_version}"
    fi
  fi
fi