#!/usr/bin/env bash

SCRIPT_PATH=$( cd "$(dirname "$0")" ; pwd -P )

IMAGE_NAME="jwilder/nginx-proxy"
IMAGE_VERSION="latest"

SERVICE_NAME=nginx-proxy


source ${SCRIPT_PATH}/../common.shinc

#
# Project specific variables
#

source ${SCRIPT_PATH}/env.shinc 2> /dev/null


init() {
	__init

	NETWORKS=(${PROXY_NETWORK})
	__createNetworks

	__build || return $?

	# Create the nginx-proxy container
	docker create \
		--name ${SERVICE_NAME} \
		-v /var/run/docker.sock:/tmp/docker.sock:ro \
		--restart=unless-stopped \
		-p 80:80 \
		-p 443:443 \
		--net ${PROXY_NETWORK} \
		${SERVICE_NAME}:latest

	[[ $? -ne 0 ]] && return 1

	__ask_to_start
}

fix() {
	local upperDir=$(docker inspect ${SERVICE_NAME} --format "{{.GraphDriver.Data.UpperDir}}")
	[[ $? -ne 0 ]] && __err "Could not determine the nginx proxy filesystem path" && return 2

	stop
	sudo rm $(docker inspect ${SERVICE_NAME} --format "{{.GraphDriver.Data.UpperDir}}")/etc/nginx/conf.d/default.conf

	if [[ $? -eq 0 ]]; then
		__success "Succesfully removed the nginx configuration, restart the container"
		return 0
	else
		__err "Could not remove the configuration file"
		return 1
	fi
}

"$@"

exit $?
