#!/bin/bash
set -euo pipefail

. driglibash-base

JC_ENV=/etc/jeancloud.env

dns_certs_path=/data/dnscerts.jean-cloud.org/certs/live
http_certs_path=/etc/letsencrypt/live
proxy_dir=/etc/nginx

cat > "$JC_ENV" <<EOF
proxy_dir='$proxy_dir'
nginx_conf_path='$proxy_dir/sites-enabled/'
new_nginx_conf_path='$proxy_dir/new-sites-enabled'
dns_certs_path='$dns_certs_path'
http_certs_path='$http_certs_path'
dummy_cert_path='$http_certs_path/dummy'
servicefile=/docker/services.csv
services_uid_start=2000
EOF
	
while IFS=';' read -r id username service server    
do
	dir="/docker/$service"
    [ ! -d "$dir" ] && continue    

	line_in_file "HTTP_DIR='/srv/http/$service'" "$dir/.env"
	line_in_file "DATA_DIR='/data/$service'" "$dir/.env"
	line_in_file "SECRET_DIR='/data/secrets/$service'" "$dir/.env"
	line_in_file "DOCKER_DIR='$dir'" "$dir/.env"
	line_in_file "JC_SERVICE='$service'" "$dir/.env"
	#line_in_file "HOME='/data/$service'" "$dir/.env"
	line_in_file "NET='172.29.$id'" "$dir/.env"
	line_in_file "USER='$username'" "$dir/.env"
	line_in_file "JC_ID='$id'" "$dir/.env"

	cert="$(findcert.sh "$service")" || true
	if [ -n "$cert" ] ; then
		line_in_file "JC_CERT='$cert'" "$dir/.env"
	fi
		
done < <(grep -v '^#' /docker/services.csv)    
