#!/bin/bash

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

RUN_PASS_DIR="secret"
TMPL_PASS_DIR="secret.tmpl"
RUN_PASS_FILE="${RUN_PASS_DIR}/SetAllPass.sh"
TMPL_PASS_FILE="${TMPL_PASS_DIR}/SetAllPass.sh"
NEED_GEN=

########################################

usage () {
    echo "Usage: $0 [-n] [-h]"
    echo "  -h help"
    exit 1
}

case "$1" in
    '-h' | '-help' )
	usage
	;;
esac

[ "$#" -eq 0 ] || usage

########################################
# check system

for prg in kompare; do
    if ! type "${prg}" > /dev/null; then
	printKazError "$0 need ${prg}"
	echo "please run \"apt-get install ${prg}\""
	exit
    fi
done

cd "${KAZ_ROOT}"
########################################
# get lvalues in script
getVars () {
    # $1 : filename
    grep "^[^#]*=" $1 | sed 's/\([^=]*\).*/\1/' | sort -u
}

# get lvalues in script
getSettedVars () {
    # $1 : filename
    grep "^[^#]*=..*" $1 | grep -v '^[^#]*=".*--clean_val--.*"' | grep -v '^[^#]*="${' | sort -u
}

getVarFormVal () {
    # $1 searched value
    # $2 filename
    grep "^[^#]*=$1" $2 | sed 's/\s*\([^=]*\).*/\1/'
}

########################################
# synchronized SetAllPass.sh (find missing lvalues)
updatePassFile () {
    # $1 : ref filename
    # $2 : target filename

    REF_FILE="$1"
    TARGET_FILE="$2"
    NEED_UPDATE=
    while : ; do
	declare -a listRef listTarget missing
	listRef=($(getVars "${REF_FILE}"))
	listTarget=($(getVars "${TARGET_FILE}"))
	missing=($(comm -23 <(printf "%s\n" ${listRef[@]}) <(printf "%s\n" ${listTarget[@]})))
	if [ -n "${missing}" ]; then
	    echo "missing vars in  ${YELLOW}${BOLD}${TARGET_FILE}${NC}:${RED}${BOLD}" ${missing[@]} "${NC}"
	    read -p "Do you want to add them? [y/n]: " yn
            case $yn in
		""|[Yy]*)
		    emacs "${REF_FILE}" "${TARGET_FILE}"
		    NEED_UPDATE=true
		    break
		    ;;
		[Nn]*)
		    break
		    ;;
	    esac
	else
	    break
	fi
    done
}

updatePassFile "${TMPL_PASS_FILE}" "${RUN_PASS_FILE}"
[ -n "${NEED_UPDATE}" ] && NEED_GEN=true
updatePassFile "${RUN_PASS_FILE}" "${TMPL_PASS_FILE}"

########################################
# check empty pass in TMPL_PASS_FILE
declare -a settedVars
settedVars=($(getSettedVars "${TMPL_PASS_FILE}"))
if [ -n "${settedVars}" ]; then
    echo "unclear password in  ${YELLOW}${BOLD}${TMPL_PASS_FILE}${NC}:${BLUE}${BOLD}"
    for var in ${settedVars[@]}; do
	echo -e "\t${var}"
    done
    echo "${NC}"
    read -p "Do you want to clear them? [y/n]: " yn
    case $yn in
	""|[Yy]*)
	    emacs "${TMPL_PASS_FILE}"
	    ;;
    esac
fi

########################################
# check new files env-*
createMissingEnv () {
    # $1 : ref dir
    # $2 : target dir
    REF_DIR="$1"
    TARGET_DIR="$2"
    NEED_UPDATE=

    declare -a listRef listTarget missing
    listRef=($(cd "${REF_DIR}"; ls -1 env-* | grep -v '~$'))
    listTarget=($(cd "${TARGET_DIR}"; ls -1 env-* | grep -v '~$'))
    missing=($(comm -23 <(printf "%s\n" ${listRef[@]}) <(printf "%s\n" ${listTarget[@]})))
    for envFile in ${missing[@]}; do
	read -p "Do you want to create ${GREEN}${BOLD}${TARGET_DIR}/${envFile}${NC}? [y/n]: " yn
	case $yn in
	    ""|[Yy]*)
		cp "${REF_DIR}/${envFile}" "${TARGET_DIR}/${envFile}"
		NEED_UPDATE=true
		;;
	esac
    done
}

createMissingEnv "${RUN_PASS_DIR}" "${TMPL_PASS_DIR}"
[ -n "${NEED_UPDATE}" ] && NEED_GEN=true
createMissingEnv "${TMPL_PASS_DIR}" "${RUN_PASS_DIR}"
[ -n "${NEED_UPDATE}" ] && NEED_GEN=true

########################################
# check missing values in env-* between RUN and TMPL
declare -a listTmpl listRun listCommonFiles
listTmplFiles=($(cd "${TMPL_PASS_DIR}"; ls -1 env-* | grep -v '~$'))
listRunFiles=($(cd "${RUN_PASS_DIR}"; ls -1 env-* | grep -v '~$'))
listCommonFiles=($(comm -3 <(printf "%s\n" ${listTmplFiles[@]}) <(printf "%s\n" ${listRunFiles[@]})))
for envFile in ${listCommonFiles[@]}; do
    while : ; do
	TMPL_FILE="${TMPL_PASS_DIR}/${envFile}"
	RUN_FILE="${RUN_PASS_DIR}/${envFile}"
	declare -a listRef list2Target missingInRun missingInTmpl
	listTmplVars=($(getVars "${TMPL_FILE}"))
	listRunVars=($(getVars "${RUN_FILE}"))
	missingInTmpl=($(comm -23 <(printf "%s\n" ${listTmplVars[@]}) <(printf "%s\n" ${listRunVars[@]})))
	missingInRun=($(comm -13 <(printf "%s\n" ${listTmplVars[@]}) <(printf "%s\n" ${listRunVars[@]})))
	if [ -n "${missingInTmpl}" ] || [ -n "${missingInRun}" ]; then
	    [ -n "${missingInTmpl}" ] &&
		echo "missing vars in ${YELLOW}${BOLD}${TMPL_FILE}${NC}:${RED}${BOLD}" ${missingInTmpl[@]} "${NC}"
	    [ -n "${missingInRun}" ] &&
		echo "missing vars in ${YELLOW}${BOLD}${RUN_FILE}${NC}:${RED}${BOLD}" ${missingInRun[@]} "${NC}"
	    read -p "Do you want to add them? [y/n]: " yn
            case $yn in
		""|[Yy]*)
		    emacs "${TMPL_FILE}" "${RUN_FILE}"
		    [ -n "${missingInTmpl}" ] && NEED_GEN=true
		    break
		    ;;
		[Nn]*)
		    break
		    ;;
	    esac
	else
	    break
	fi
    done
done

########################################
# check empty pass in env-*
for envFile in $(ls -1 "${TMPL_PASS_DIR}/"env-* | grep -v '~$'); do
    settedVars=($(getSettedVars "${envFile}"))
    if [ -n "${settedVars}" ]; then
	echo "unclear password in  ${GREEN}${BOLD}${envFile}${NC}:${BLUE}${BOLD}"
	for var in ${settedVars[@]}; do
	    echo -e "\t${var}"
	done
	echo "${NC}"
	read -p "Do you want to clear them? [y/n]: " yn
	case $yn in
	    ""|[Yy]*)
		emacs "${envFile}"
		;;
	esac
    fi
done

########################################
# check extention in dockers.env
declare -a missing
missing=($(for DIR in "${RUN_PASS_DIR}" "${TMPL_PASS_DIR}"; do
	       for envFile in $(ls -1 "${DIR}/"env-* | grep -v '~$'); do
		   val="${envFile#*env-}"
		   varName=$(getVarFormVal "${val}" "${DOCKERS_ENV}")
		   if [ -z "${varName}" ]; then
		       echo "${val}"
		   fi
	       done
	   done | sort -u))
if [ -n "${missing}" ]; then
    echo "missing def in  ${GREEN}${BOLD}${DOCKERS_ENV}${NC}:${BLUE}${BOLD}"
    for var in ${missing[@]}; do
	echo -e "\t${var}"
    done
    echo "${NC}"
    read -p "Do you want to add them? [y/n]: " yn
    case $yn in
	""|[Yy]*)
	    emacs "${DOCKERS_ENV}"
	    ;;
    esac
fi

########################################
# check env-* in updateDockerPassword.sh
missing=($(for DIR in "${RUN_PASS_DIR}" "${TMPL_PASS_DIR}"; do
	       for envFile in $(ls -1 "${DIR}/"env-* | grep -v '~$'); do
		   val="${envFile#*env-}"
		   varName=$(getVarFormVal "${val}" "${DOCKERS_ENV}")
		   [ -z "${varName}" ] && continue
		   prefixe=$(grep "^\s*updateEnv.*${varName}" "${KAZ_BIN_DIR}/updateDockerPassword.sh" |
				 sed 's/\s*updateEnv[^"]*"\([^"]*\)".*/\1/' | sort -u)
		   if [ -z "${prefixe}" ]; then
		       echo "${envFile#*/}_(\${KAZ_KEY_DIR}/env-\${"${varName}"})"
		   fi
	       done
	   done | sort -u))
if [ -n "${missing}" ]; then
    echo "missing update in  ${GREEN}${BOLD}${KAZ_BIN_DIR}/updateDockerPassword.sh${NC}:${BLUE}${BOLD}"
    for var in ${missing[@]}; do
	echo -e "\t${var}"
    done
    echo "${NC}"
    read -p "Do you want to add them? [y/n]: " yn
    case $yn in
	""|[Yy]*)
	    emacs "${KAZ_BIN_DIR}/updateDockerPassword.sh"
	    ;;
    esac
fi

########################################
# synchronized SetAllPass.sh and env-*
updateEnvFiles () {
    # $1 secret dir
    DIR=$1
    listRef=($(getVars "${DIR}/SetAllPass.sh"))
    missing=($(for envFile in $(ls -1 "${DIR}/"env-* | grep -v '~$'); do
		   val="${envFile#*env-}"
		   varName=$(getVarFormVal "${val}" "${DOCKERS_ENV}")
		   [ -z "${varName}" ] && continue
		   prefixe=$(grep "^\s*updateEnv.*${varName}" "${KAZ_BIN_DIR}/updateDockerPassword.sh" |
				 sed 's/\s*updateEnv[^"]*"\([^"]*\)".*/\1/' | sort -u)
		   [ -z "${prefixe}" ] && continue
		   listVarsInEnv=($(getVars "${envFile}"))
		   for var in ${listVarsInEnv[@]}; do
		       [[ ! " ${listRef[@]} " =~ " ${prefixe}_${var} " ]] && echo "${prefixe}_${var}"
		   done
		   # XXX doit exister dans SetAllPass.sh avec le prefixe
	       done))
    if [ -n "${missing}" ]; then
	echo "missing update in  ${GREEN}${BOLD}${DIR}/SetAllPass.sh${NC}:${BLUE}${BOLD}"
	for var in ${missing[@]}; do
	    echo -e "\t${var}"
	done
	echo "${NC}"
	read -p "Do you want to add them? [y/n]: " yn
	case $yn in
	    ""|[Yy]*)
		emacs "${DIR}/SetAllPass.sh"
		;;
	esac
    fi
}

updateEnvFiles "${RUN_PASS_DIR}"
updateEnvFiles "${TMPL_PASS_DIR}"

# XXX chercher les variables non utilisées dans les SetAllPass.sh

if [ -n "${NEED_GEN}" ]; then
    while : ; do
	read -p "Do you want to generate blank values? [y/n]: " yn
	case $yn in
	    ""|[Yy]*)
	    	"${KAZ_BIN_DIR}/secretGen.sh"
		break
		;;
	    [Nn]*)
		break
		;;
	esac
    done
fi


# XXX config/dockers.tmpl.env


# XXX ! vérifier init pour dockers.env