#!/bin/bash

function delete(){
  echo "Deleting resources..."
  oc delete sub  -n openshift-operators project-quay
  oc delete csvs -n openshift-operators --all
  echo "Done"
}

function watchCsvStatus(){
  version=$1
  fullName=quay-operator.$version
  echo "Checking status of $fullName..."
  command="oc get csv -n openshift-operators $fullName -o jsonpath={.status.phase}"
  while true; do
    status=$($command 2> /dev/null)
    printf "Current Status: $status\033[0K\r"
    if [[ $status == "Succeeded" || $status == "Failed" ]]; then
      watchResult=$status
      echo
      return 0
    fi
    # If we're stuck in this loop then it's likely the issue has been reproduced
    sleep 2
  done
}

function recreate(){

  oc create -f - <<EOF
apiVersion: operators.coreos.com/v1alpha1
kind: Subscription
metadata:
  creationTimestamp: "2023-07-27T16:31:27Z"
  generation: 4
  labels:
    operators.coreos.com/project-quay.openshift-operators: ""
  name: project-quay
  namespace: openshift-operators
  resourceVersion: "204058"
  uid: 75908d46-1f32-4ee2-8f67-32eec19ca061
spec:
  channel: stable-3.6
  installPlanApproval: Automatic
  name: project-quay
  source: community-operators
  sourceNamespace: openshift-marketplace
EOF

}

function patch(){
  version=$1
  oc patch -n openshift-operators sub project-quay -p "{\"spec\":{\"channel\":\"stable-$version\"}}" --type merge
}

delete
declare -i iterations
# A couple notes for whoever uses this:
# 1. These if statements don't actually catch the repro, instead the script will hang in
#    watchCsvStatus while it waits for the CSV to report "Succeeded". I'm keeping them
#    in though for completeness.
# 2. The version numbers for each watchCsvStatus call are hard-coded to the version
#    numbers that were 'latest' from each channel at the time, and it's very possible 
#    they could change. If that's the case, just update them to match the version in the 
#    CSV that gets created after the channel switch.
while true; do
  iterations+=1
  recreate
  watchCsvStatus v3.6.2
  if [[ $watchResult == "Failed" ]]; then
    echo "Bug was reproduced; exiting"
    exit 0
  fi
  patch 3.7
  watchCsvStatus v3.7.11
  if [[ $watchResult == "Failed" ]]; then
    echo "Bug was reproduced; exiting"
    exit 0
  fi
  patch 3.8
  watchCsvStatus v3.8.10
  if [[ $watchResult == "Failed" ]]; then
    echo "Bug was reproduced; exiting"
    exit 0
  fi
  delete
  echo "Iterations: $iterations"
done

