#!/bin/bash
. driglibash-base
. /etc/jeancloud.env


[ ! -f /data/mounted ] && die "/data is not mounted"

noreload=false
deploy=true
service=
if [ "$#" -ge 2 ] && [ "$2" = noreload ] ; then
	noreload=true
fi
if [ "$#" -ge 3 ] && [ "$3" = undeploy ] ; then
	deploy=false
fi
# die "Usage: $0 <service> [no]reload [un]deploy"


if [ -d "/docker/$1" ] ; then
	service="$1"
elif [ -d "$1" ] && [[ "$1" = /docker/* ]] ; then
	service="$(basename "$1")"
else
	die "service $1 not found"
fi

if [ ! -d "$new_nginx_conf_path" ] ; then
	die "Can’t deploy service in degraded state. $new_nginx_conf_path dir is missing, please run deployall.sh first"
fi

IFS=';' read id username _ server < <(grep ";$service;" /docker/services.csv)
if [ -z "$id" ] ; then
	die "Service $service not found in list"
fi

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

docker_service="$(echo "$service" | tr '.' '_')"
driglibash_section_prefix="[$service] "
section "---------- Start -------------"

cd "/docker/$service"


# Source and export env file
[ -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 scripts
###############################################################################

# Did deploy failed
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 containers
###############################################################################

# If there is a docker-compose file and it has services in it
if [ -f "/docker/$service/docker-compose.yml" ] && [ -n "$(grep  '^[^#]*services' "/docker/$service/docker-compose.yml")" ] ; then
	if $deploy ; then
    	section "Logging to registry"
    	# XXX Login to docker registry

    	section "Pulling images"
    	docker-compose pull
		if [ "$?" -ne 0 ] ; then
			echo "PULL FAILED"
		fi

    	section "Starting service"
    	run docker-compose up -d --remove-orphans
		[ "$?" -ne 0 ] && echo "Erreur docker compose" && returncode=1
	else
		section "Removing containers"
    	run docker-compose down --rmi all --remove-orphans
	fi
fi

if ! "$deploy" ; then
	section "Remove stray containers"
	while read container ; do
		[ -z "$container" ] && continue || true
		echo "Removing $container"
		run docker rm "$container"
	done <<< "$(docker ps | grep "$docker_service" | cut -d ' ' -f 1)"
fi



###############################################################################
#							wireguard interface
###############################################################################

# If there is a wireguard vpn script
for file in $( find "/docker/$service" -name "wgns-*.sh") ; do
	section "Managing wg interface $(basename "$file")"
    if [ -x "$file" ] ; then
        wgif="$(basename "$file")"
        wgif="${wgif:5:-3}"
		if [ -z "$wgif" ] ; then
			echo "No wireguard name for $file"
			returncode=1
			continue
		fi
        "$file" $wgif > "/etc/wireguard/$wgif.conf"
		if "$deploy" ; then
        	#run systemctl enable "wg-quick@$wgif"
        	run managewg.sh start "$wgif"
			[ "$?" -ne 0 ] && echo "Erreur wireguard" && returncode=1
		else
        	run managewg.sh stop "$wgif"
		fi
    fi
done

# If there is a wireguard vpn template
for file in $( find "/docker/$service" -name "wg-*.sh") ; do
	section "Creating wg iface $(basename "$file")"
    if [ -x "$file" ] ; then
        wgif="$(basename "$file")"
        wgif="${wgif:3:-3}"
		if [ -z "$wgif" ] ; then
			echo "No wireguard name for $file"
			returncode=1
			continue
		fi
		#run template.sh "/docker/$service/.env" < "$file" > "/etc/wireguard/$wgif.conf"
        "$file" $wgif > "/etc/wireguard/$wgif.conf"

		if "$deploy" ; then
        	run systemctl enable "wg-quick@$wgif"
        	run startwg.sh start "$wgif"
			[ "$?" -ne 0 ] && echo "Erreur wireguard" && returncode=1
		else
        	run managewg.sh stop "$wgif"
		fi
    fi
done


###############################################################################
#							Nginx conf
###############################################################################

# If there is a nginx conf file
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/$service"

fi

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

if [ "$noreload" == false ] ; then
	run restart_nginx.sh
fi


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

clean
exit "$returncode"
