#!/bin/bash

. /usr/share/univention-lib/ldap.sh

set -e
eval "$(ucr shell)"

while [ $# -gt 0 ]; do
    case "$1" in
        "--error-file")
            shift
            errorfile="$1"
            shift
            ;;
        "--old-version")
            shift
            old_version="$1"
            shift
            ;;
        "--version")
            shift
            version="$1"
            shift
            ;;
        "--binddn")
            shift
            binddn="$1"
            shift
            ;;
        "--bindpwdfile")
            shift
            bindpwdfile="$1"
            shift
            ;;
        *)
            shift
            ;;
    esac
done


if [ -n "$old_version" ]; then
    # this is an update. everything below this if is only important for new installations
    exit 0
fi


mkdir -p  "/var/lib/univention-appcenter/apps/dcd/conf/dcdrediscert"


python3 <<-%EOF
import os
import bz2
import json
import base64
import hashlib
import secrets
import univention.admin.uldap
from univention.config_registry.frontend import ucr_update
from univention.config_registry import ConfigRegistry

ucr = ConfigRegistry()
ucr.load()
conf_path = "/var/lib/univention-appcenter/apps/dcd/conf/"

def create_api_token():
    apitoken = secrets.token_urlsafe(72)
    filename = "/var/lib/univention-appcenter/apps/dcd/conf/apitoken.secret"
    with open(filename, 'w+') as outfile:
        outfile.write(apitoken)
    os.chown(filename, 0, 0)
    os.chmod(filename, 0o600)

def write_acls(replicapwd, apiuserpwd):
    pwds = {}

    pwds['dcdreplica'] = secrets.token_urlsafe(72)
    if replicapwd:
        pwds['dcdreplica'] = replicapwd
    pwds['dcdapiuser'] = secrets.token_urlsafe(72)
    if apiuserpwd:
        pwds['dcdapiuser'] = apiuserpwd
    hashes = {}

    for i in pwds.keys():
        filename = "/var/lib/univention-appcenter/apps/dcd/conf/%s.secret" %(i,)
        with open(filename, 'w+') as outfile:
            outfile.write(pwds[i])
        os.chown(filename, 0, 0)
        os.chmod(filename, 0o600)

    def hashpasswords(pwds):
        for name, pwd in pwds.items():
            h = hashlib.new('sha256')
            h.update(pwd.encode('ascii'))
            sha = h.hexdigest()
            hashes[name] = sha


    hashpasswords(pwds)
    aclfile = '/var/lib/univention-appcenter/apps/dcd/conf/users.acl'
    with open(aclfile, 'w+') as outfile:
        # create replica
        line = "user default on #%s resetchannels -@all +psync +replconf +ping\n" %(hashes['dcdreplica'],)
        line += "user dcdapiuser on #%s ~* &* +@all -@dangerous -@slow -@admin -@scripting -@transaction +keys +@keyspace +@pubsub +set\n" %(hashes['dcdapiuser'])

        outfile.write(line)
    os.chown(filename, 0, 0)
    os.chmod(filename, 0o600)


with open("$bindpwdfile") as fd:
    bindpwd = fd.read().rstrip()

lo = univention.admin.uldap.access(host=ucr.get("ldap/server/name"), port=ucr.get("ldap/master/port"), base=ucr.get("ldap/base"), binddn="$binddn", bindpw=bindpwd)
obj = lo.search(filter="(&(univentionObjectType=settings/data)(cn=dcdconfig))", base=lo.base, attr=["univentionData"])

if obj:
    print("primary dcd redis server exists, become replica")
    primary_settings = obj[0][1]["univentionData"][0]
    primary_settings = json.loads(bz2.decompress(primary_settings).decode('UTF-8'))
    pwd = primary_settings.pop("passwords")
    certs = primary_settings.pop("certificates")

    print("fetch secrets")
    replicapwd = pwd.get("dcdreplica")
    apiuserpwd = pwd.get("dcdapiuser")
    write_acls(replicapwd, apiuserpwd)

    filename = "dcdrediscert"
    path = "%s%s" % (conf_path, filename)
    if not os.path.exists(path):
        os.makedirs(path)
    os.chown(path, 0, 0)
    os.chmod(path, 0o700)

    print("fetch certificates")
    for name, cert in certs.items():
        filename = "%s/%s" % (path, name)
        with open(filename, 'w+') as outfile:
            outfile.write(cert)
        os.chown(filename, 0, 0)
        os.chmod(filename, 0o600)
    # set primary host to first entry in installations
    ucr_update(ucr, {"dcd/redis/primary/host": primary_settings["installations"][0]})
    ucr_update(ucr, {"dcd/redis/replication/mode": "replica"})
else:
    print("no primary dcd redis server exists, become primary")
    write_acls(None, None)
    ucr_update(ucr, {"dcd/redis/replication/mode": "master"})
    ucr_update(ucr, {"dcd/redis/primary/password/file": "%sdcdreplica.secret" % (conf_path,)})
    ucr_update(ucr, {"dcd/redis/primary/apiuser/password/file": "%sdcdapiuser.secret" % (conf_path,)})

create_api_token()
ucr_update(ucr, {"dcd/api/token/password/file": "%s%s" % (conf_path, "apitoken.secret")})
ucr_update(ucr, {"dcd/redis/primary/password/file": "%sdcdreplica.secret" % (conf_path,)})
ucr_update(ucr, {"dcd/redis/primary/apiuser/password/file": "%sdcdapiuser.secret" % (conf_path,)})

%EOF


CONF_PATH="/var/lib/univention-appcenter/apps/dcd/conf/"
filename="dcdrediscert/"
cert_path="$CONF_PATH$filename"
generate_cert() {
    local name=$1

    local keyfile="$cert_path"private.key
    local certfile="$cert_path"cert.pem

    [ -f $keyfile ] || openssl genrsa -out $keyfile 4096
    openssl req \
        -new -sha256 \
        -subj "/O=Redis/CN=Univention" \
        -key $keyfile | \
        openssl x509 \
            -req -sha256 \
            -CA "$cert_path"ca.crt \
            -CAkey "$cert_path"ca.key \
            -CAserial "$cert_path"ca.txt \
            -CAcreateserial \
            -days 29220 \
            -out $certfile
}

if [[ "$(ucr get dcd/redis/replication/mode)" = "master" ]]; then
    openssl genrsa -out "$cert_path"ca.key 4096
    openssl req \
        -x509 -new -nodes -sha256 \
        -key "$cert_path"ca.key \
        -days 29220 \
        -subj '/O=Redis/CN=Certificate Authority' \
        -out "$cert_path"ca.crt

    generate_cert
fi

ucr set dcd/redis/tls/cert="$cert_path"cert.pem
ucr set dcd/redis/tls/key="$cert_path"private.key
ucr set dcd/redis/tls/ca="$cert_path"ca.crt

exit 0
