#!/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_bindpwdfile_from_args() {
    ## parse binddn and bindpwdfile 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
                ;;
            "--bindpwdfile")
                bindpwdfile="${2:?missing bindpwdfile}"
                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
     --bindpwdfile str    LDAP bind password file for bind dn
__USAGE__
}

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

[ $(univention-ldapsearch -xLLL '(&(isOXUser=OK)(!(oxContextIDNum=*)))' 1.1 | wc -l) -eq 0 ] && exit 0

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) --csv \
| awk -F ","  '"'"' \
NR==1 {
    for (i=1; i<=NF; i++) {
        f[$i] = i
    }
}
{ if (NR!=1) print $(f["PrimaryEmail"]) }
  '"'"' \
| xargs -I{} univention-ldapsearch -xLLL '"'"'(&(&(mailPrimaryAddress={})(isOXUser=OK))(!(oxContextIDNum=*)))'"'"' 1.1 \
| sed -ne '"'"'s,dn: ,,p'"'"' >> dns_ctx{}.txt '

echo "Modifying users:"

while read -r context ; do
    echo "Context $context:"
    while read -r dn; do
       udm users/user modify --dn $dn  --set oxContext=$context ${binddn:+--binddn $binddn} ${bindpwdfile:+--bindpwdfile $bindpwdfile} ;
    done < dns_ctx$context.txt
    rm dns_ctx$context.txt
done < ctxs.txt

rm ctxs.txt
echo "Done"

