#!/bin/sh

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin


CONFIG_ROOT="/etc/cauth-ldap-slave-slapd-config"
YANDEX_ENVIRONMENT=$(cat /etc/yandex/environment.type)


check_yandex_environment() {
    if [ -z "${YANDEX_ENVIRONMENT}" ]
    then
        echo "ERROR: No yandex environment set, check contents of /etc/yandex/environment.type"
        exit 1
    fi
    if [ "${YANDEX_ENVIRONMENT}" = "production" ]
    then
        echo "INFO: Installing onto \"production\" Yandex environment"
    elif [ "${YANDEX_ENVIRONMENT}" = "testing" ]
    then
        echo "INFO: Installing onto \"testing\" Yandex environment"
    else
        echo "ERROR: Unknown Yandex environment, check /etc/yandex/environment.type contents."
        exit 1
    fi
} # check_yandex_environment()


configure_environment() {
    ENV_CONFIG_ROOT="${CONFIG_ROOT}/${YANDEX_ENVIRONMENT}"

    # Stop 'slapd-instances' service.
    service slapd-instances stop || true

    # Remove 'slapd-instances' service symlinks.
    rm -v /etc/default/slapd-instances-config || true
    rm -v /etc/init.d/slapd-instances || true

    # Remove symlinks to instances config files.
    for INSTANCE_CONFIG in "${ENV_CONFIG_ROOT}"/instance-*.conf
    do
        CONFIG_BNAME=$(basename "${INSTANCE_CONFIG}")
        rm -v "${CONFIG_ROOT}/${CONFIG_BNAME}" || true
    done
}  # configure_environment()


do_configure() {
    if [ "${YANDEX_ENVIRONMENT}" = "production" ]
    then
        configure_environment
    fi
    if [ "${YANDEX_ENVIRONMENT}" = "testing" ]
    then
        echo "ERROR: Testing environment is not supported yet."
        # configure_environment
        exit 1
    fi
} # do_configure()


case "$1" in
    remove|upgrade|deconfigure)
    check_yandex_environment
    do_configure
    ;;

    failed-upgrade)
    ;;

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

exit 0
