## NGINX library
preparation
deployment
    deployment
    testing
    cleaning
restart
    restart
    testing
    cleaning        
stop

## Preparation 

driglibash_section_prefix="[Prepare nginx] "
section "Delete new conf directory (to start from scratch)"
run rm -rf "$new_nginx_conf_path"

section "Create new conf file (for tests purposes)"
sed "s#$nginx_conf_path#$new_nginx_conf_path/#" "/docker/_proxy/nginx.conf" > "$proxy_dir/new_nginx.conf"

section "Create proxy dir"
run mkdir -p "$proxy_dir" 

section "Create new conf directory"
run mkdir -p "$new_nginx_conf_path"

## deploy
### write new conf
if [ -f "/docker/$service/nginx_server.conf" ] ; then
    section "Copy nginx conf"
    run cp "/docker/$service/nginx_server.conf" "$new_nginx_conf_path/$service"

    section "Template nginx conf with vars from '.env' file"
    run template.sh "/docker/$service/.env" < "/docker/$service/nginx_server.conf" > "$new_nginx_conf_path/
    (template : 	bash -c 'set -a && . '"$1"' &&  envsubst "$(cat '"$1"' | grep -o ^.*= | sed "s/=//" | sed "s/^/$/")"')
    $service"
fi

### testing 
section "Testing nginx conf"
run nginx -t -c /etc/nginx/new_nginx.conf
[ "$?" -ne 0 ] && echo "Erreur nginx" && returncode=1

### replace old conf

section "Update nginx conf"
run rm -rf "$nginx_conf_path"
run cp -r "$new_nginx_conf_path" "$nginx_conf_path"
run cp "/docker/_proxy/nginx.conf" "$proxy_dir/nginx.conf"

### sane testing
section "Test nginx conf to be sure"
run nginx -t

## restart or start
if [ -z "$(cat /var/run/nginx.pid)" ] ; then
    section "Start nginx"
    run nginx
else
    section "Reload nginx"
    run nginx -s reload
fi

## cleaning
section "Cleaning"
rmdir "$DATA_DIR" "$HTTP_DIR" 2>/dev/null || true

