#!/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/>.
#

. /usr/share/univention-ox/ox-lib.sh || exit 1

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
                ;;
            "--removed-files")
                removedfiles="OK"
                shift 1 || 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
     --removed-files       Confirm that 'remove-empty-oxContext-entries' has been executed in the ox-connector server.
__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

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."
    echo
    /var/lib/univention-appcenter/apps/ox-connector/data/resources/remove-empty-oxContext-entries
else
    if [ -z "$removedfiles" ]; then
        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."
        echo "If you already did this rerun this script with --removed-files"
        die 2
    fi
fi


echo "The script will check that all users have the oxContext attribute assigned."
echo "It may take some time if there are a lot of users..."
echo
/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\" with the dns of these users has been generated for each ox context."
echo "Modifying users:"

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

echo "Done"

