#!/bin/bash

# preinst - Script preinst called before installation and update
# Seafile benötigt eine MySQL-Passwort-Datei unter /var/lib/univention-appcenter/apps/seafile/conf/mysql_password.secret
# Falls die Passwort-Datei noch nicht existiert, wird diese entweder...
# a) wiederhergestellt (falls Seafile schon früher installiert war)
# b) oder neu erzeugt
# wenn die Datei existiert, passiert nichts.

echo $(date +%c): MySQL-Passwort-Datei
APP_DIR="/var/lib/univention-appcenter/apps/seafile"
MYSQL_PASSWORD_FILE="${APP_DIR}/conf/mysql_password.secret"
MYSQL_COMPOSE_ENV="${APP_DIR}/compose/.env"
HIT=`find /var/lib/univention-appcenter/backups/appcenter-backup-seafile* -maxdepth 0 -type d -print | wc -l`

if [ -e ${APP_DIR}/conf/mysql_password.secret ]; then
  echo "mysql_password.secret already exists (Update)"
  MYSQL_SECRET=`cat ${APP_DIR}/conf/mysql_password.secret`

else
  mkdir -p ${APP_DIR}/{conf,compose}

  if [[ ${HIT} > 0 ]]; then
    echo "I found ${HIT} seafile backups (Restore from backup)"
    echo "[IMPORTANT] If your seafile is not working, probably the mysql-password is wrong and you can not access the database"
    MYSQL_SECRET=`find /var/lib/univention-appcenter/backups/appcenter-backup-seafile*/conf/mysql_password.secret -type f -printf '%T+ %p\n' | sort | head -n 1 | cut -d' ' -f2 | xargs cat`

  else
    echo "There are no seafile backups (First installation)"
    MYSQL_SECRET=`pwgen -s 64 1 | tr -d '\n'`

  fi

  # write mysql_password.secret
  echo "${MYSQL_SECRET}" > ${MYSQL_PASSWORD_FILE}

fi

# write compose/.env and set permissions
echo "MYSQL_ROOT_PASSWORD=${MYSQL_SECRET}" > ${MYSQL_COMPOSE_ENV}
chown root:root ${MYSQL_PASSWORD_FILE}
chmod 400 ${MYSQL_PASSWORD_FILE}
chown root:root ${MYSQL_COMPOSE_ENV}
chmod 400 ${MYSQL_COMPOSE_ENV}

exit 0