#!/usr/bin/env dash

# concat all customs certs in
{{- if or (eq (printf "%v" .Values.bootstrap.sslVerify) "true") (eq (printf "%v" .Values.bootstrap.sslVerify) "True") }}
{{- if .Values.global.customCACerts }}
    # copy system certs to a temp file
    # then concat our custom certs to that file
    cp -pur {{ include "cmem.cmemc-ca-bundle-path" . }} /custom-cacert/customcacerts.pem
    echo "Copied python system CAs from {{ include "cmem.cmemc-ca-bundle-path" . }}"
    cat /custom-cacert/cm/* >> /custom-cacert/customcacerts.pem
    echo "Concat custom CA to new system CA"
    echo "Now using this REQUESTS_CA_BUNDLE: ${REQUESTS_CA_BUNDLE}"
{{- end }}
{{- end }}

# ensure CMEM is kind of up and responding
while ! cmemc graph list; do
echo "Waiting for 'cmemc graph list' to succeed ... retry in 10 seconds ..."
sleep 10
done
echo "CMEM should be up now. Initiating bootstrap process ..."

# ensure "cmemc admin status"
while ! cmemc admin status --exit-1 error; do
echo "Waiting for 'cmemc admin status --exit-1 error' to succeed ... retry in 10 seconds ..."
# bootstrap the instance again, in case we failed due to 'ValueError: Your ShapeCatalog version does not match your DataPlatform version. Please consider updating your bootstrap data.'

cmemc admin migration list
cmemc admin migration execute --all
sleep 10
done
echo "'cmemc admin status' succeeded ... we should be good to release this instance."

{{- if .Values.bootstrap.defaultUser.enabled }}
# manage default user
echo "Next, create the user \"$NEW_USER_NAME\" ..."
cmemc admin user create $NEW_USER_NAME
{{- if .Values.bootstrap.defaultUser.email }}
cmemc admin user update $NEW_USER_NAME --email $NEW_USER_EMAIL
{{- end }}

{{- if .Values.bootstrap.defaultUser.password }}
echo "Update password  {{ if .Values.bootstrap.defaultUser.temporaryPassword }} --temporary {{ end }}"
cmemc admin user password $NEW_USER_NAME --value $NEW_USER_PASSWORD {{ if .Values.bootstrap.defaultUser.temporaryPassword }}--temporary{{ end }}
{{- end }}
{{- if .Values.bootstrap.defaultUser.passwordSendMail }}
echo "Update password and request passwordchange per mail"
cmemc admin user password $NEW_USER_NAME --value Hahpeisahng8Fushohxo --request-change 
{{- end }}

{{- if .Values.bootstrap.defaultUser.isAdmin }}
echo "Next, add user to admin groups"
cmemc admin user update $NEW_USER_NAME --assign-group elds-admins
cmemc admin user update $NEW_USER_NAME --assign-group local-admins
{{- end }}

echo "Done. User \"$NEW_USER_NAME\" is set up."
{{- end }}

{{- if .Values.bootstrap.pythonPlugins.enabled }}
# install/upgrade plugins
plugins="{{ .Values.dataintegration.config.pythonPlugins | join " " }}"
for plugin in $plugins; do
    echo "Install/upgrade plugin: $plugin ..."
    cmemc admin workspace python install $plugin
done
{{- end }}
