#!/bin/bash

DOCKER_NAME=$1
UP_DOWN=$2
CH_NAME=$3

function printHelp () {
	echo "Usage: ./network_setup cli|orderer0 <up|down> <channel-name>"
}

function validateArgs () {
        if [ -z "${DOCKER_NAME}" ]; then 
		echo "Option cli / orderer0 not mentioned"
		printHelp
		exit 1
	fi
	if [ -z "${UP_DOWN}" ]; then
		echo "Option up / down / restart not mentioned"
		printHelp
		exit 1
	fi
	if [ -z "${CH_NAME}" ]; then
		echo "setting to default channel 'mychannel'"
		CH_NAME=mychannel
	fi
}

function clearContainers () {
        CONTAINER_IDS=$(docker ps -aq)
        if [ -z "$CONTAINER_IDS" -o "$CONTAINER_IDS" = " " ]; then
                echo "---- No containers available for deletion ----"
        else
                docker rm -f $CONTAINER_IDS
        fi
}

function removeUnwantedImages() {
        DOCKER_IMAGE_IDS=$(docker images | grep "dev\|none\|test-vp\|peer[0-9]-" | awk '{print $3}')
        if [ -z "$DOCKER_IMAGE_IDS" -o "$DOCKER_IMAGE_IDS" = " " ]; then
                echo "---- No images available for deletion ----"
        else
                docker rmi -f $DOCKER_IMAGE_IDS
        fi
}

function networkUp () {
	if [ "${DOCKER_NAME}" == "cli" ]; then
		COMPOSE_FILE=docker-compose-cli.yaml
	elif [ "${DOCKER_NAME}" == "orderer0" ]; then
		COMPOSE_FILE=docker-compose-orderer0.yaml
	else
		echo "Option cli /orderer0 not mentioned"
		exit 1
	fi

	CHANNEL_NAME=$CH_NAME docker-compose -f $COMPOSE_FILE up -d 2>&1
	if [ $? -ne 0 ]; then
		echo "ERROR !!!! Unable to pull the images "
		exit 1
	fi

	if [ "${DOCKER_NAME}" == "cli" ]; then
		docker logs -f cli
	fi
}

function networkDown () {
	if [ "${DOCKER_NAME}" == "cli" ]; then
		COMPOSE_FILE=docker-compose-cli.yaml
	elif [ "${DOCKER_NAME}" == "orderer0" ]; then
		COMPOSE_FILE=docker-compose-orderer0.yaml
	else
		COMPOSE_FILE=
	fi
        docker-compose -f $COMPOSE_FILE down
        #Cleanup the chaincode containers
	clearContainers
	#Cleanup images
	removeUnwantedImages
}

validateArgs

#Create the network using docker compose
if [ "${UP_DOWN}" == "up" ]; then
	networkUp
elif [ "${UP_DOWN}" == "down" ]; then ## Clear the network
	networkDown
elif [ "${UP_DOWN}" == "restart" ]; then ## Restart the network
	networkDown
	networkUp
else
	printHelp
	exit 1
fi
