#! /usr/bin/env bash
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
USER_HOME=$HOME
[[ -n "${SUDO_USER}" ]] && USER_HOME="$(eval "echo ~${SUDO_USER}")"
. ${SHRC_D:-$SCRIPT_DIR}/01_util.functions 

set -e

get_charts() {
    midclt call chart.release.query | jq -r '
        del(.[] 
        | select( .status == "STOPPED" or (.id|inside(
            "traefik",
            "plex-pms"
          ))
        ))
        | .[].id
    '
}

stop_chart() {
    local CHART="${1}"
    printf 'Stopping charts: %s... ' "$CHART"
    midclt call chart.release.scale "$CHART" '{"replica_count": 0}'
    printf '\n'
}

stop_all_charts() {
    get_charts | while read chart; do
        [[ -n "$chart" ]] || continue
        stop_chart "$chart"
    done
}

count_unfinished_jobs() {   
    midclt call core.get_jobs | jq -r '.[] | select( .time_finished == null )' | wc -l
}

while [[ "$( get_charts | wc -l )" -gt 0 ]]; do
    stop_all_charts

    while [[ "$( count_unfinished_jobs )" -gt 0 ]]; do
        printf '.'
        sleep 2
    done
    printf '\n'
done