#!/bin/sh
# preinst script for ymc-mysql-config
#
# see: dh_installdeb(1)

set -e

# summary of how this script can be called:
#        * <new-preinst> `install'
#        * <new-preinst> `install' <old-version>
#        * <new-preinst> `upgrade' <old-version>
#        * <old-preinst> `abort-upgrade' <new-version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package

case "$1" in
  install|upgrade)
    . /usr/lib/lib-ymc/ymc-mysql-tools.sh

    ### Check for "fliwi-get-my-services"
    if [ "$(which fliwi-get-my-services)" = '' ]; then
      ymc_error_msg "Command 'fliwi-get-my-services' not found..."
      return 1
    fi

    ### Check if the replication-setup-script exists (needed in post)
    if [ "$(which ymc-mysql-setup-auto-import-mysql-backupdata)" = '' ]; then
      ymc_error_msg "Command 'ymc-mysql-setup-auto-import-mysql-backupdata' not found!"
      exit 1
    fi

    ### Check if the freshly-replication-setup-script exists (needed in post)
    if [ "$(which ymc-mysql-setup-replication-from-freshly-installed-mysql-master)" = '' ]; then
      ymc_error_msg "Command 'ymc-mysql-setup-replication-from-freshly-installed-mysql-master' not found!"
      exit 1
    fi

    ### Check if the permission-setup-script exists (needed in post)
    if [ "$(which ymc-mysql-setup-create-mysql-users)" = '' ]; then
      ymc_error_msg "Command 'ymc-mysql-setup-create-mysql-users' not found!"
      exit 1
    fi

    service=$(get_own_db_service)
    if [ $? -ne 0 ]; then
      ymc_error_msg "Failed to determine the installed db-service. Please check if exactly one is present!"
      exit 1
    fi


    ### Check if our config-dir is present
    for my_numbered_service in $(fliwi-get-my-services)
    do
      my_service=$(echo $my_numbered_service | sed -r 's/-[0-9]+$//')
      if [ -z "$my_service" ]; then
        continue
      fi
      fliwi-config-update --service $my_service || true
    done
    service_based_config_dir=$(get_service_base_config_dir)
    if [ $? -ne 0 ] || \
       [ "$service_based_config_dir" = "" ]; then
      ymc_error_msg "Failed to calculate the service-based config-dir"
      exit 1
    fi

    if [ ! -d "$service_based_config_dir" ]; then
      ymc_error_msg "Config dir '$service_based_config_dir' missing"
    fi
  ;;

  abort-upgrade)
  ;;

  *)
    echo "preinst called with unknown argument \`$1'" >&2
    exit 1
  ;;
esac

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0
