#!/usr/bin/env bash
set -e

WORKLOAD_UPDATE_METHODS=$(oc get hyperconverged kubevirt-hyperconverged -n openshift-cnv -ojsonpath='{.spec.workloadUpdateStrategy.workloadUpdateMethods}')
echo "Workload Update Methods: ${WORKLOAD_UPDATE_METHODS}"

function wait_for_hco {
    oc wait --for=condition=Upgradeable=False hyperconverged kubevirt-hyperconverged -n openshift-cnv --timeout 60s
    oc wait --for=condition=Upgradeable=True hyperconverged kubevirt-hyperconverged -n openshift-cnv --timeout 60s
    oc wait --for=condition=Available=True deployment hco-webhook -n openshift-cnv --timeout 60s
}

function reset_migrations {
    echo "Disable workload update methods in HCO"
    oc patch hyperconverged kubevirt-hyperconverged -n openshift-cnv --type json -p '[{"op":"replace","path":"/spec/workloadUpdateStrategy/workloadUpdateMethods", "value":[]}]'

    echo "Wait for patch to be applied via HCO"
    wait_for_hco

    echo "Scale down HCO Operator, Virt Operator, and Virt Controller"
    oc scale --replicas=0 deployment -n openshift-cnv hco-operator
    oc scale --replicas=0 deployment -n openshift-cnv virt-operator
    oc scale --replicas=0 deployment -n openshift-cnv virt-controller

    while [[ $(oc get pod -n openshift-cnv -l kubevirt.io=virt-controller --no-headers| wc -l) -gt 0 ]]; do sleep 5; done
    oc scale --replicas=0 deployment -n openshift-cnv hco-webhook

    echo "Verify number of Running VMs and Wait for pod count to match VM count"
    VM_COUNT=$(oc get vm -A --no-headers | grep -E '(Running|Migrating)' | wc -l)
    echo "VM Count: ${VM_COUNT}"
    while [[ $(oc get pod -A -l kubevirt.io=virt-launcher --no-headers | grep Running | wc -l) -ne ${VM_COUNT} ]]; do sleep 5; done


    echo "Remove non-successful migrations"
    oc get vmim -A --no-headers | grep -v Succeeded | awk '{ print $1 " " $2; }' | xargs -I{} bash -c 'oc delete vmim -n {} --wait=false'
    oc get vmim -A --no-headers | grep -v Succeeded | awk '{ print $1 " " $2; }' | xargs -I{} bash -c 'oc patch vmim -n {} --type=json --patch "[{ \"op\": \"replace\", \"path\": \"/metadata/finalizers\", \"value\": [] }]"'
    oc get vmim -A --no-headers | grep -v Succeeded | awk '{ print $1 " " $2; }' | xargs -I{} bash -c 'oc delete vmim -n {} --wait=true'

    echo "Scale CNV back up"
    oc scale --replicas=1 deployment -n openshift-cnv hco-operator
    wait_for_hco

    echo "Re-enable LiveMigrate"
    HCO_PATCH="[{\"op\":\"replace\",\"path\":\"/spec/workloadUpdateStrategy/workloadUpdateMethods\", \"value\":${WORKLOAD_UPDATE_METHODS}}]"
    oc patch hyperconverged kubevirt-hyperconverged -n openshift-cnv --type json -p "${HCO_PATCH}"
    wait_for_hco

}

echo "Monitor for failed migrations..."
while [[ true ]]; do
    FAILED_MIGRATIONS=$(oc get vmim -n default --no-headers | grep Failed | wc -l)
    if [[ ${FAILED_MIGRATIONS} -gt 0 ]]; then
        echo "${FAILED_MIGRATIONS} Failed migrations detected"
        reset_migrations
        echo "Return to monitoring for failed migrations..."
    fi
    sleep 30
done
