
## checks if service on server 

failed=""

while IFS=';' read -r id username service target
do

	echo -n "$service -> "
    [ ! -d "/docker/$service" ] && die "/docker/$service directory not found"

	# Check if service target is localhost
	[[ "$(getent hosts $target)" != "::1 "* ]] && echo 'Not here' && continue
	
	echo "Deploying"
    deploy_service.sh "$service" "noreload"

	if [ "$?" -ne 0 ] ; then
		failed="$failed $service"
	fi

done < <(grep -v '^#' /docker/services.csv)   


## user id
uid="$(($services_uid_start + $id))"

## environment variables

[ -f .env ] && set -a && . .env && set +a
[ -f "$SECRET_DIR/.env" ] && set -a && . "$SECRET_DIR/.env" && set +a

## useful directories 

if "$deploy" ; then
	run mkdir -p "$DATA_DIR" "$HTTP_DIR"
	run chown $uid "$DATA_DIR"
	run chmod 751 "$DATA_DIR"
	run chown $uid:www-data -R "$HTTP_DIR"
	if [ -d "$SECRET_DIR" ] ; then
		run chown $uid "$SECRET_DIR" -R
		run chmod 751 "$SECRET_DIR" -R
	fi
else
    [ -d "$HTTP_DIR" ] && rm -r "$HTTP_DIR"
fi

## run bash scripts

returncode=0
if "$deploy" ; then
	if [ -x deploy.sh ] ; then
		run ./deploy.sh
		[ "$?" -ne 0 ] && echo "Erreur deploy.sh" && returncode=1
	fi
	if [ -x deploy_user.sh ] ; then
		deploy_as "$service"
		[ "$?" -ne 0 ] && echo "Erreur deploy_user.sh" && returncode=1
	fi
else
	[ -x undeploy.sh ] && run ./undeploy.sh
fi


## docker 

if [ -f "/docker/$service/docker-compose.yml" ] && [ -n "$(grep  '^[^#]*services' "/docker/$service/docker-compose.yml")" ] ; then
// launch docker deploy

## nginx

if [ -f "/docker/$service/nginx_server.conf" ] ; then
//launch nginx deploy 

## wireguard

if [ -f  "/docker/$service" -name "wg-*.sh" ]
//launch wg deploy