#!/bin/bash -eux
dry_run="$(config-get dry-run)"
chaos_dir="$(config-get chaos-dir)"
exclude_command="$(action-get exclude-command)"
exclude_group="$(action-get exclude-group)"
enablement_timeout="$(action-get enablement-timeout)"
include_command="$(action-get include-command)"
include_group="$(action-get include-group)"
total_timeout="$(action-get total-timeout)"
monkey_id="$(action-get monkey-id)"
mode="$(action-get mode)"
monkey_id=${monkey_id:-${JUJU_ACTION_TAG#action-}}
action-set action-parameters.dry-run="${dry_run}"
action-set action-parameters.chaos-dir="${chaos_dir}"
action-set action-parameters.charm-dir="${CHARM_DIR}"
action-set action-parameters.exclude-command="${exclude_command}"
action-set action-parameters.exclude-group="${exclude_group}"
action-set action-parameters.enablement-timeout="${enablement_timeout}"
action-set action-parameters.include-command="${include_command}"
action-set action-parameters.include-group="${include_group}"
action-set action-parameters.monkey-id=${monkey_id}
action-set action-parameters.total-timeout="${total_timeout}"
action-set action-parameters.mode="${mode}"

# Create a unique directory to run and log this monkeys actions.
target_dir=${chaos_dir}/chaos_monkey.${monkey_id}
mkdir -p ${target_dir}/log
if [[ -d ${CHARM_DIR}/chaos-monkey ]]; then
    cp -a ${CHARM_DIR}/chaos-monkey ${target_dir}
fi

# Run the Chaos Monkey
cmd="python ${target_dir}/chaos-monkey/runner.py"
cmd+=" ${target_dir}"
if [[ -n ${exclude_command:-} ]]; then
    cmd+=" --exclude-command ${exclude_command}"
fi
if [[ -n ${exclude_group:-} ]]; then
    cmd+=" --exclude-group ${exclude_group}"
fi
if [[ -n ${include_command:-} ]]; then
    cmd+=" --include-command ${include_command}"
fi
if [[ -n ${include_group:-} ]]; then
    cmd+=" --include-group ${include_group}"
fi
if [[ -n ${total_timeout:-} ]]; then
    cmd+=" --total-timeout ${total_timeout}"
fi
if [[ -n ${enablement_timeout:-} ]]; then
    cmd+=" --enablement-timeout ${enablement_timeout}"
fi
if [[ -n ${mode:-} && "single" == "$mode" ]]; then
    cmd+=" --run-once"
fi
action-set action-info.runner-cmd="${cmd}"
action-set action-info.runner-log="${target_dir}/log/results.log"
if [[ ${dry_run-} != True ]]; then
    # Start the Chaos runner in a subprocess with nohup and in the background.
    # In this way it's PPID becomes init and further juju actions are not
    # blocked.
    (nohup ${cmd} >> ${target_dir}/log/nohup.out 2>&1 &)
fi
