#!/bin/bash
#
# Creates and runs container with SAYMON analytics module.
#

# Fail on first error.
set -e

#
# Outputs a log message.
#
# Parameters:
# 1: Log message.
#
log() {
  echo ">> $1"
}

#
# Runs a given action and retries until it succeeds.
#
# Parameters:
# 1: Command to run.
# [2]: Command to recover from error.
#
function withRetry() {
  local -r -i MAX_ATTEMPTS=50
  local -i ATTEMPT_NUM=1
  local -i TIMEOUT=3

  until . /dev/stdin <<< $1
  do
    if [ -n "$2" ]; then
      log "Failed, will run command \"$2\" and wait $TIMEOUT seconds..."
      $2
    else
      log "Failed, will retry in $TIMEOUT seconds..."
    fi

    if (( ATTEMPT_NUM == MAX_ATTEMPTS )); then
      log "Maximum number of retries reached, failing."
      exit 1
    else
      (( ATTEMPT_NUM++ ))
      sleep $TIMEOUT
    fi
  done
}


DIR=$(cd "$( dirname "$0" )" && pwd)
CONFIG=/etc/saymon/saymon-server.conf
VAR=/var/saymon
if [ -z "$CONTAINER_NAME" ]; then
  CONTAINER_NAME=saymon-analytics
fi

# Install Docker if needed.
if [ -z "`which docker`" ] ; then
  log "Installing Docker..."

  $DIR/../scripts/install-docker.sh || exit 1
fi

# Create folder to store SAYMON analytics module socket file if needed.
if [ ! -d "$VAR" ] ; then
  log "Creating "$VAR" dir..."

  sudo mkdir "$VAR"
fi

# Pull Docker Image with specific tag.
if [ -z "$ANALYTICS_BRANCH" ]; then
  ANALYTICS_BRANCH=master
fi

if [ "$RERUN" = "true" ]; then
docker stop $CONTAINER_NAME > /dev/null
docker rm $CONTAINER_NAME > /dev/null
fi

log "Pulling saymon-public/analytics:$ANALYTICS_BRANCH..."
withRetry "docker pull portus.saymon.info/saymon-public/analytics:$ANALYTICS_BRANCH"
withRetry "docker run -d --name=$CONTAINER_NAME \
    -v $VAR:$VAR \
    -v $CONFIG:$CONFIG:ro \
    --network=host \
    --restart=unless-stopped portus.saymon.info/saymon-public/analytics:$ANALYTICS_BRANCH"

log "Container with SAYMON analytics module successfully launched!"
