#!/bin/bash

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

RUN_PASS_DIR="secret"
TMPL_PASS_DIR="secret.tmpl"
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 -E "^[^=#]*(USER|PASS|TOKEN|DATABASE|ACCOUNT|LOGIN|KEY)[^#]*=..*" ./* |  grep -vE '^[^#=]*=.*@@(user|pass|db|token|gv|cv)@@.*' | sort -u
}

getUnsettedVars () {
    # $1 : filename
	grep -vE '^[^#=]*=.*@@(user|pass|db|token|gv|cv)@@.*' ./* | sort -u
}

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


########################################
# 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 -12 <(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 extention in dockers.env
declare -a missing
unsetted=($(for DIR in "${RUN_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




if [ -n "${NEED_GEN}" ]; then
    while : ; do
	read -p "Do you want to generate missing 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



