#!/bin/sh -e
#
# dc - docker compose manager
# usage: `dc caddy restart`
#
# ---
# source: https://git.cyberia.club/reese/admin-scripts/src/branch/main/bin/dc

if [ "$1" = "-h" ] || [ "$1" = "--help" ] || [ "$1" = "help" ]; then
  printf '%s\n' "\
usage: $(basename "$0") <stack_name> <create | echo | edit | logs | start | status | [any other 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
