#!/bin/bash

cd $(dirname $0)/..

mkdir -p emptySecret
rsync -aHAX --info=progress2 --delete secret/ emptySecret/

cd emptySecret/

. ../config/dockers.env
. ./SetAllPass.sh

# pour mise au point
# SIMU=echo

cleanEnvDB(){
    # $1 = prefix
    # $2 = envName
    # $3 = containerName of DB
    rootPass="--root_password--"
    dbName="--database_name--"
    userName="--user_name--"
    userPass="--user_password--"

    ${SIMU} sed -i \
	    -e "s/MYSQL_ROOT_PASSWORD=.*/MYSQL_ROOT_PASSWORD=${rootPass}/g" \
	    -e "s/MYSQL_DATABASE=.*/MYSQL_DATABASE=${dbName}/g" \
	    -e "s/MYSQL_USER=.*/MYSQL_USER=${userName}/g" \
	    -e "s/MYSQL_PASSWORD=.*/MYSQL_PASSWORD=${userPass}/g" \
	    "$2"
}

cleanEnv(){
    # $1 = prefix
    # $2 = envName    
    for varName in $(grep "^[a-zA-Z_]*=" $2 | sed "s/^\([^=]*\)=.*/\1/g")
    do
	srcName="$1_${varName}"
	srcVal="--clean_val--"
	${SIMU} sed -i \
		-e "s~^[ ]*${varName}=.*$~${varName}=${srcVal}~" \
		"$2"
    done
}

cleanPasswd(){
    ${SIMU} sed -i \
	    -e 's/^\([# ]*[^#= ]*\)=".[^{][^"]*"/\1="--clean_val--"/g' \
	    ./SetAllPass.sh
}

####################
# main

# read -r -p "Do you want to remove all password? [Y/n] " input
 
# case $input in
#     [yY][eE][sS]|[yY])
#  echo "Remove all password"
#  ;;
#     [nN][oO]|[nN])
#  echo "Abort"
#        ;;
#     *)
#  echo "Invalid input..."
#  exit 1
#  ;;
# esac

cleanPasswd

cleanEnvDB "etherpad" "./env-${etherpadDBName}" "${etherpadDBName}"
cleanEnvDB "framadate" "./env-${framadateDBName}" "${framadateDBName}"
cleanEnvDB "git" "./env-${gitDBName}" "${gitDBName}"
cleanEnvDB "mattermost" "./env-${mattermostDBName}" "${mattermostDBName}"
cleanEnvDB "nextcloud" "./env-${nextcloudDBName}" "${nextcloudDBName}"
cleanEnvDB "roundcube" "./env-${roundcubeDBName}" "${roundcubeDBName}"
cleanEnvDB "sso" "./env-${ssoDBName}" "${ssoDBName}"
cleanEnvDB "sympa" "./env-${sympaDBName}" "${sympaDBName}"
cleanEnvDB "vigilo" "./env-${vigiloDBName}" "${vigiloDBName}"
cleanEnvDB "wp" "./env-${wordpressDBName}" "${wordpressDBName}"

cleanEnv "etherpad" "./env-${etherpadServName}"
cleanEnv "gandi" "./env-gandi"
cleanEnv "jirafeau" "./env-${jirafeauServName}"
cleanEnv "mattermost" "./env-${mattermostServName}"
cleanEnv "nextcloud" "./env-${nextcloudServName}"
cleanEnv "office" "./env-${officeServName}"
cleanEnv "roundcube" "./env-${roundcubeServName}"
cleanEnv "sso" "./env-${ssoServName}"
cleanEnv "vigilo" "./env-${vigiloServName}"
cleanEnv "wp" "./env-${wordpressServName}"

cat > allow_admin_ip <<EOF
# ip for admin access only

# local test
allow 127.0.0.0/8;
allow 192.168.0.0/16;

EOF

chmod -R go= .
chmod -R +X .
