#!/usr/bin/env bash

set -eo pipefail; [[ $DOKKU_TRACE ]] && set -x

source "$PLUGIN_CORE_AVAILABLE_PATH/common/functions"

validate_dependencies() {
  if ! command -v "ansible-playbook" &>/dev/null; then
    log-fail "Missing ansible-playbook, run dokku plugin:install-dependencies"
  fi
}

function run_playbook() {
  local app="$1"
  local play_path="$2"
  local requirements="$3"
  local vault_file="$DOKKU_LIB/ansible/$app/.vault.sh"

  validate_dependencies

  if [[ ! -f "$play_path" ]]; then
    dokku_col_log_info1_quiet "$play_path not found or executable bit not set"
    exit 0
  fi

  if [[ -f "$requirements" ]]; then
    dokku_col_log_info1_quiet "$requirements file found"
    ansible-galaxy install --role-file "$requirements"
  fi

  dokku_col_log_info1_quiet "Copying library modules into place"
  mkdir -p $DOKKU_ROOT/.ansible/{roles,plugins/modules}
  cp -R $DOKKU_ROOT/.ansible/roles/*/library/* $DOKKU_ROOT/.ansible/plugins/modules

  local args="--inventory $(hostname), --connection local"

  if [[ -f "$vault_file" ]]; then
    dokku_col_log_info1_quiet "$vault_file file found"
    args+=" --vault-password-file \"$vault_file\""
  fi

  dokku_col_log_info1_quiet "$play_path file found"
  ansible-playbook "$args" "$play_path"
}