#!/bin/bash

## Init is run on host
## For now it is run every time the script is launched, but
## it should be launched only once after build.

## Accessible variables are:
## - SERVICE_NAME        Name of current service
## - DOCKER_BASE_IMAGE   Base image from which this service might be built if any
## - SERVICE_DATASTORE           Location on host of the DATASTORE of this service
## - SERVICE_CONFIGSTORE         Location on host of the CONFIGSTORE of this service


set -e

. lib/common

mode="$(options-get mode)" || exit 1

case "$mode" in
    single)
        capacity="$(options-get capacity)" || exit 1
        init-config-add "\
$MASTER_BASE_SERVICE_NAME:
  environment:
    DRONE_RUNNER_CAPACITY: $capacity
  volumes:
    - /var/run/docker.sock:/var/run/docker.sock
"
    ;;
    multi)
        secret="$(options-get secret)" || {
            err "In 'multi' mode, you must set a 'secret' in $DARKYELLOW$SERVICE_NAME$NORMAL service's" \
                "options to share with slave drones."
            echo "  You can use: 'openssl rand -hex 16' to create one." >&2
            exit 1
        }
        init-config-add "\
$MASTER_BASE_SERVICE_NAME:
  environment:
    DRONE_RPC_SECRET: $secret
"

        ;;
esac


admin="$(options-get admin)" || exit 1
if [ "$admin" ]; then
    init-config-add "\
$MASTER_BASE_SERVICE_NAME:
  environment:
    DRONE_USER_CREATE: \"username:$admin,admin:true\"
"
fi


init-config-add "\
$MASTER_BASE_SERVICE_NAME:
  environment:
    DRONE_SERVER_HOST: $MASTER_BASE_SERVICE_NAME
    DRONE_SERVER_PROTO: http
"