#!/bin/bash
#
#
# Copyright (C) 2013-2023 Univention GmbH <http://www.univention.de/>
#
# All rights reserved.
#
# The source code of this program is made available
# under the terms of the GNU Affero General Public License version 3
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this program provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention and not subject to the GNU AGPL V3.
#
# In the case you use this program under the terms of the GNU AGPL V3,
# the program is provided in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <http://www.gnu.org/licenses/>.
#

extract_binddn_and_bindpwd_from_args() {
	## parse binddn and bindpwd from command line arguments into shell variables
	while [ $# -gt 0 ]; do
		case "$1" in
            "--help|-h") usage ; exit 0 ;;
			"--binddn")
				binddn="${2:?missing binddn}"
				shift 2 || exit 2
				;;
            "--bindpwd")
				bindpwd="${2:?missing bindpwd}"
				shift 2 || exit 2
				;;
			*)
				shift
				;;
		esac
	done
}

usage () {
	cat <<-__USAGE__
	usage: [options] Repair user oxContext attributes

	Options:
	 --help, -h           Show this help
	 --binddn str         LDAP bind dn for UDM CLI operation
	 --bindpwd str        LDAP bind password for bind dn
__USAGE__
}

if [ "$(ucr get server/role)" != "domaincontroller_master" ]; then
    extract_binddn_and_bindpwd_from_args "$@"
    if [ -z "$binddn" ||  -z "$bindpwd" ]; then
        die 2 "The script is not running on the primary server. Run --binddn and --bindpwd arguments"
    fi
fi

echo "The script will check that all users have the oxContext attribute assigned."
echo "It may take some time if there are many users."

/opt/open-xchange/sbin/listcontext -P $(< /etc/ox-secrets/master.secret) -A oxadminmaster | awk 'NR>1 { print $1; }' > ctxs.txt
cat ctxs.txt | xargs -I{} bash -c '/opt/open-xchange/sbin/listuser -c {} -A $(if [[ {} == 10 ]]; then echo "oxadmin"; else echo "oxadmin-context{}"; fi) -P $(< /etc/ox-secrets/context{}.secret) \
| awk '"'"'NR > 1 { print $5; }'"'"' \
| xargs -I{} univention-ldapsearch -xLLL '"'"'(&(&(mailPrimaryAddress={})(isOXUser=OK))(!(oxContextIDNum=*)))'"'"' 1.1 \
| sed -ne '"'"'s,dn: ,,p'"'"' >> dns_ctx{}.txt '

echo "Completed. A file called \"dns_ctx$ID.txt\" has been generated for each context."
echo "The files contains the dns of the users without oxContext."
echo "Next, the users are going to be modified."

#Needs credentials
while read -r context ; do
    while read -r dn; do
       udm users/user modify --dn $dn  --set oxContext=$context ${binddn:+--binddn $binddn} ${bindpwd:+--bindpwd $bindpwd} ;
    done < dns_ctx$context.txt
done < ctxs.txt

#Run locally if possible.
echo "Done."

inst=$(python3 <<EOF
from univention.appcenter.app_cache import Apps
ox_connector = Apps().find('ox-connector')
print(str(ox_connector.is_installed()).lower())
EOF
)

if $inst; then
    echo "Running the script '/var/lib/univention-appcenter/apps/ox-connector/data/resources/remove-empty-oxContext-entries'"
    echo "to remove old listener entries that prevent the ox-connector application from operating correctly."
    /var/lib/univention-appcenter/apps/ox-connector/data/resources/remove-empty-oxContext-entries
else
    echo "Run the script '/var/lib/univention-appcenter/apps/ox-connector/data/resources/remove-empty-oxContext-entries'"
    echo "In the host where the ox-connector app is installed to finish the fix of the attribute."
fi
