#!/bin/bash

KAZ_ROOT=$(cd "$(dirname $0)/.."; pwd)
. "${KAZ_ROOT}/bin/.commonFunctions.sh"
setKazVars

cd "${KAZ_ROOT}"

NEW_DIR="secret"
TMPL_DIR="secret.tmpl"

if [ ! -d "${NEW_DIR}/" ]; then
    rsync -a "${TMPL_DIR}/" "${NEW_DIR}/"
fi

NEW_FILE="${NEW_DIR}/SetAllPass-new.sh"
TMPL_FILE="${NEW_DIR}/SetAllPass.sh"

while read line ; do
    if [[ "${line}" =~ ^# ]] || [ -z "${line}" ] ; then
	echo "${line}"
	continue
    fi
    if [[ "${line}" =~  "--clean_val--" ]] ; then
	case "${line}" in
	    *jirafeau_DATA_DIR*)
		JIRAFEAU_DIR=$(getValInFile "${DOCKERS_ENV}" "jirafeauDir")
		[ -z "${JIRAFEAU_DIR}" ] &&
		    echo "${line}" ||
			sed "s%\(.*\)--clean_val--\(.*\)%\1${JIRAFEAU_DIR}\2%" <<< ${line}
		continue
		;;
	    *DATABASE*)
		dbName="$(sed "s/\([^_]*\)_.*/\1/" <<< ${line})_$(apg -n 1 -m 2 -M NCL | cut -c 1-2)"
		sed "s/\(.*\)--clean_val--\(.*\)/\1${dbName}\2/" <<< ${line}
		continue
		;;
	    *ROOT_PASSWORD*|*PASSWORD*)
		pass="$(apg -n 1 -m 16 -M NCL)"
		sed "s/\(.*\)--clean_val--\(.*\)/\1${pass}\2/" <<< ${line}
		continue
		;;
	    *USER*)
		user="$(sed "s/\([^_]*\)_.*/\1/" <<< ${line})_$(apg -n 1 -m 2 -M NCL | cut -c 1-2)"
		sed "s/\(.*\)--clean_val--\(.*\)/\1${user}\2/" <<< ${line}
		continue
		;;
	    *RAIN_LOOP*|*office_password*|*mattermost_*|*sympa_*|*gitea_*)
		pass="$(apg -n 1 -m 16 -M NCL)"
		sed "s/\(.*\)--clean_val--\(.*\)/\1${pass}\2/" <<< ${line}
		continue
		;;
	    *vaultwarden_ADMIN_TOKEN*)
		pass="$(apg -n 1 -m 32 -M NCL)"
		sed "s/\(.*\)--clean_val--\(.*\)/\1${pass}\2/" <<< ${line}
		continue
		;;
	esac
    else
	echo "${line}"
	continue
    fi
    printKazError "${line}" >&2
done < "${TMPL_FILE}" > "${NEW_FILE}"

mv "${NEW_FILE}" "${TMPL_FILE}"

chmod a+x "${TMPL_FILE}"
. "${TMPL_FILE}"
"${KAZ_BIN_DIR}/updateDockerPassword.sh"

exit 0