#!/bin/sh

VERSION=1

. /usr/share/univention-lib/base.sh
. /usr/share/univention-lib/ldap.sh
. /usr/share/univention-join/joinscripthelper.lib

local_is_ucr_false () { # test if UCS variable is "true" or "false"
    local value
    value="$(univention-config-registry get "$1")"
    case "$(echo -n "$value" | tr '[:upper:]' '[:lower:]')" in
        1|yes|on|true|enable|enabled) return 1 ;;
        0|no|off|false|disable|disabled) return 0 ;;
        *) return 2 ;;
    esac
}

joinscript_init
eval "$(univention-config-registry shell)"

if ! local_is_ucr_false suitecrm/keepdatabase; then
   /usr/bin/mysql -u root -p$(cat /etc/mysql.secret) <<EOF
DROP DATABASE IF EXISTS suitecrm;
DELETE FROM mysql.user where User="suitecrm";
FLUSH PRIVILEGES;
EOF
   echo "INFO: database suitecrm deleted"
else
   echo "INFO: database suitecrm and mysql user suitecrm kept, please remove manually"
fi

if ! local_is_ucr_false suitecrm/keepfiles; then
   rm -r /var/lib/suitecrm
   rm -r /var/lib/suitecrm_etc
   echo "INFO: suitecrm files deleted"
else
   echo "INFO: suitecrm files kept, please remove manually /var/lib/suitecrm and /var/lib/suitecrm_etc directories"
fi

SERVICE="SuiteCRM"
ucs_removeServiceFromLocalhost "${SERVICE}" "$@"
if ucs_isServiceUnused "${SERVICE}" "$@"; then
       univention-directory-manager container/cn remove "$@" --dn "cn=DIGITEC SuiteCRM Attributes,cn=custom attributes,cn=univention,$ldap_base"

       stop_udm_cli_server
fi

# Remove old join script from index file otherwise the re-installation will not work
joinscript_remove_script_from_status_file digitec-suitecrm

exit 0
