#!/bin/sh

set -e

# docker compose manager
# example: dc caddy restart

if [ "$1" = "help" ]; then
  echo "usage: dc <stack_name> <create | echo | edit | logs | start | status | [any other docker compose command]>"
  exit 1
fi

service="$1"
shift
action="$1"
if [ -z "${service}" ] || [ -z "${action}" ]; then
  echo "the first two arguments can't be empty"
  exit 1
fi
shift
args="$*"

COMPOSE_ROOT="${COMPOSE_ROOT:-/opt/compose}"
mkdir -p "${COMPOSE_ROOT}"

case "${action}" in
  create)
    mkdir "${COMPOSE_ROOT}/${service}" || exit 1
    printf '%b\n' "services:\n  ${service}:\n    restart: unless-stopped\n    image: \n    environment:\n      \n    ports:\n      - \n    volumes:\n      - " >"${COMPOSE_ROOT}/${service}/docker-compose.yml"
    ${EDITOR:-vi} "${COMPOSE_ROOT}/${service}/docker-compose.yml"
    ;;
  echo)
    echo "${service} ${action} ${args}"
    ;;
  edit)
    ${EDITOR:-vi} "${COMPOSE_ROOT}/${service}/docker-compose.yml"
    ;;
  logs)
    cd "${COMPOSE_ROOT}/${service}" && docker compose logs -f "${args}"
    ;;
  start)
    cd "${COMPOSE_ROOT}/${service}" && docker compose up -d "${args}"
    ;;
  status)
    cd "${COMPOSE_ROOT}/${service}" && docker compose ps "${args}"
    ;;
  *)
    cd "${COMPOSE_ROOT}/${service}" && docker compose "${action}" "${args}"
    ;;
esac
