#!/bin/sh

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

CERTS_DIR="/etc/cauth-ldap-certs"
OPENLDAP_USER="openldap"
OPENLDAP_GROUP="openldap"
YAV_DEPLOY_CONFIG_FILE="/etc/yandex/yav-deploy/cauth-ldap-certs.conf"


add_openldap_user_group() {
    if [ -z "$(getent group ${OPENLDAP_GROUP})" ]; then
        addgroup --quiet --system ${OPENLDAP_GROUP}
    fi
    if [ -z "$(getent passwd openldap)" ]; then
        echo "\n  Creating new user openldap... " >&2
        adduser --quiet --system --home /var/lib/ldap --shell /bin/false \
            --ingroup ${OPENLDAP_GROUP} --disabled-password --disabled-login \
            --gecos "Symas LDAP Server Account" ${OPENLDAP_USER}
        echo "done." >&2
    fi
}  # add_openldap_user_group()


run_yav_deploy() {
   yav-deploy \
    --file "${YAV_DEPLOY_CONFIG_FILE}" \
    --rsa-login="${YAV_DEPLOY_USERNAME}" \
    --debug
}

add_openldap_user_group

printf "\n* Postinstall script is going to launch 'yav-deploy' and receive a secret.\n"
printf "* Ensure that you have 'ForwardAgent yes' in ~/.ssh/config on your PC.\n"
printf "* SSH keys in ssh-agent:\n"
ssh-add -l
printf "\n* We need your username to go to Yandex Vault.\n"
printf "* Please enter your Yandex username below:\n"
read YAV_DEPLOY_USERNAME

printf "\n* Launching 'yav-deploy' with configuration file ${YAV_DEPLOY_CONFIG_FILE}\n\n"

if run_yav_deploy; then
    printf "\n* Successfully received secrets from Yandex Vault.\n\n"
else
    printf "\n* Failure receiving secrets from Yandex Vault.\n\n"
fi

if id -u ${OPENLDAP_USER} > /dev/null 2>&1; then
    chown --verbose ${OPENLDAP_USER} ${CERTS_DIR}/*.crt || true
    chown --verbose ${OPENLDAP_USER} ${CERTS_DIR}/*.pem || true
else
    printf "* No ${OPENLDAP_USER}, leaving owner of certificates in ${CERTS_DIR} as is.\n"
fi

if id -g ${OPENLDAP_GROUP} > /dev/null 2>&1; then
    chgrp --verbose ${OPENLDAP_GROUP} ${CERTS_DIR}/*.crt || true
    chgrp --verbose ${OPENLDAP_GROUP} ${CERTS_DIR}/*.pem || true
else
    printf "* No ${OPENLDAP_USER}, leaving group of certificates in ${CERTS_DIR} as is.\n"
fi

