#!/bin/bash

set -e

display_help() {
  echo "Nexus Mods Development Tools"
    echo " "
    echo "commands:"
    echo "down                        Stops a docker-compose service"
    echo "up                          Starts a docker-compose service in the background"
    echo "build                       Builds the local image(s) for a docker-compose service. Allows docker-compose build arguments"
    echo "restart                     Stops and then starts a docker-compose service"
    echo "rebuild                     Stops, builds and then starts a docker-compose service"
    echo "logs                        Shows the logs for a docker-compose service"
    echo "cq, code-quality            Runs the nexus code quality tool"
    echo "gu, gemfile-updater         Runs the gemfile updater tool, outputting common gemfiles in the console"
    echo "bu, bundle-update           Mounts the Gemfile and lockfile and runs bundle update."
    echo "-v, version                 Outputs the current version of this tool"
    echo "update                      Updates this script to the latest version."
    echo "-h, --help                  show brief help"
    echo " "
    echo "options:"
    echo "--logs                      Can be appended to up, restart or rebuild to tail the logs for the docker-compose service"
}

case "$1" in
  -h|--help)
    display_help
    exit 0
    ;;
  down)
    docker-compose down --remove-orphans
    ;;
  up)
    docker-compose up -d
    if [ "$2" == '--logs' ]
    then
    docker-compose logs -f
    fi
    ;;
  build)
    shift
    docker-compose build "$@"
    ;;
  restart)
    docker-compose down && docker-compose up  -d
    if [ "$2" == '--logs' ]
    then
    docker-compose logs -f
    fi
    ;;
  rebuild)
    docker-compose down && docker-compose build && docker-compose up  -d
    if [ "$2" == '--logs' ]
    then
    docker-compose logs -f
    fi
    ;;
  logs)
    docker-compose logs -f
    ;;
  cq|code-quality)
    shift
    docker run -v "$PWD":/app/mounted gitlab.nexdev.uk:5555/pub/nexus-code-quality/master "$@"
    ;;
  gu|gemfile-updater)
    shift
    docker run -it -v "$(pwd)":/app -v /usr/local/bundle:/usr/local/bundle gitlab.nexdev.uk:5555/pub/base-image-gemfile-updater:v1.2.0 "$@"
    ;;
  bu|bundle-update)
    shift
    docker run -it -v "$(pwd)":/app -v /usr/local/bundle:/usr/local/bundle gitlab.nexdev.uk:5555/pub/bundle-updater:v1.0.2 "$@"
    echo "Container now must be rebuilt!"
    ;;
  -v|version)
    shift
    version=`cat ~/nexus-tools/VERSION`
    echo "$version"
    ;;
  update)
    shift
    echo "Downloading new version"
    wget https://gitlab.nexdev.uk/pub/nexus-tools/-/raw/master/run.sh -O ~/nexus-tools/nexus-tools.sh
    wget https://gitlab.nexdev.uk/pub/nexus-tools/-/raw/master/NEXUS_TOOLS_VERSION -O ~/nexus-tools/VERSION
    ;;
  *)
    display_help
    ;;
esac