#!/bin/bash

WATCH_DIR=$1
WATCH_SERVICE=$2

if [[ -z "$WATCH_DIR" ]]; then
    echo '$1 directory is required!'
    exit 1
fi

# remove trailing slashes
WATCH_DIR=$(echo "$WATCH_DIR" | sed 's:/*$::')

# get all running containers
docker ps -q | while read id
do
    # extract data about docker-compose context
    WORK_DIR=$(docker inspect $id | jq -r .[0].Config.Labels.'"com.docker.compose.project.working_dir"')
    SERVICE_NAME=$(docker inspect $id | jq -r .[0].Config.Labels.'"com.docker.compose.service"')

    # if specific, only restart named service
    if [[ -n $WATCH_SERVICE && $WATCH_SERVICE != $SERVICE_NAME ]]; then
        continue
    fi

    # if container compose context matches target, restart
    if [[ $WORK_DIR == $WATCH_DIR* ]]; then
        set -x
        cd $WORK_DIR && docker-compose restart $SERVICE_NAME
        set +x
    fi
done

