#!/usr/bin/env bash
#
# This script starts Danbooru by installing Docker and Docker Compose, then
# starting Danbooru in a container. Danbooru will be available at http://localhost.
#
# Usage:
#
#     bin/danbooru up   # start Danbooru
#     bin/danbooru down # stop and remove Danbooru container.
#     bin/danbooru help # show Docker Compose help
#
# Alternatively, if you already have Docker installed, you can just do:
#
#     docker-compose up
#
# This script is just a wrapper for that command.

set -euxo pipefail

# Check if program exists.
has() {
  type -p "$1" > /dev/null
}

# Install Docker and Docker Compose if they're not installed already.
install_docker_compose() {
  if has docker && has docker-compose; then
    return
  fi

  # Debian and Ubuntu
  if has apt-get; then
    sudo apt-get update
    sudo apt-get install -y docker.io docker-compose
  # Fedora
  elif has dnf; then
    sudo dnf install -y docker docker-compose
  # Arch Linux
  elif has pacman; then
    sudo pacman -Sy --noconfirm docker docker-compose
  else
    echo "Error: Couldn't automatically install docker-compose. Install docker-compose manually."
    exit 1
  fi
}

# Start Docker if it's not running already.
start_docker() {
  if ! sudo docker version > /dev/null; then
    sudo systemctl start docker
  fi
}

install_docker_compose
start_docker
sudo docker-compose "${@:-up}"
