set -eu
K="sudo -n /usr/local/bin/kubectl"
TS=$(date +%Y%m%d%H%M%S)

echo ---backup-configmap-and-storageclass---
$K -n longhorn-system get configmap longhorn-storageclass -o yaml > /tmp/longhorn-storageclass-configmap-before-2replica-$TS.yaml
$K get storageclass longhorn -o yaml > /tmp/longhorn-storageclass-before-template-fix-$TS.yaml
ls -l /tmp/longhorn-storageclass-*-$TS.yaml

echo ---write-new-storageclass-template---
cat > /tmp/longhorn-storageclass-template-2replica.yaml <<'EOF'
kind: StorageClass
apiVersion: storage.k8s.io/v1
metadata:
  name: longhorn
  annotations:
    storageclass.kubernetes.io/is-default-class: "true"
provisioner: driver.longhorn.io
allowVolumeExpansion: true
reclaimPolicy: "Delete"
volumeBindingMode: Immediate
parameters:
  numberOfReplicas: "2"
  staleReplicaTimeout: "30"
  fromBackup: ""
  fsType: "ext4"
  dataLocality: "disabled"
  unmapMarkSnapChainRemoved: "ignored"
EOF

python3 - <<'PY'
import json, subprocess
new=open('/tmp/longhorn-storageclass-template-2replica.yaml').read()
patch={"data":{"storageclass.yaml":new}}
subprocess.check_call(["sudo","-n","/usr/local/bin/kubectl","-n","longhorn-system","patch","configmap","longhorn-storageclass","--type=merge","-p",json.dumps(patch)])
PY

echo ---verify-configmap-template---
$K -n longhorn-system get configmap longhorn-storageclass -o yaml | grep -A24 "storageclass.yaml" | sed -n "1,80p"

echo ---delete-storageclass-for-reconcile---
$K delete storageclass longhorn

echo ---wait-recreated---
recreated=no
for i in $(seq 1 30); do
  if $K get storageclass longhorn >/dev/null 2>&1; then echo recreated_after=${i}s; recreated=yes; break; fi
  sleep 1
done
if [ "$recreated" = no ]; then
  echo controller_did_not_recreate_quickly_creating_from_template
  $K create -f /tmp/longhorn-storageclass-template-2replica.yaml
fi

echo ---verify-storageclass-final---
$K get storageclass longhorn -o yaml | sed -n "1,140p"

echo ---verify-volume-health---
$K -n longhorn-system get settings.longhorn.io default-replica-count -o custom-columns=NAME:.metadata.name,VALUE:.value --no-headers
$K -n longhorn-system get volumes.longhorn.io -o custom-columns=NAME:.metadata.name,STATE:.status.state,ROBUSTNESS:.status.robustness,REP:.spec.numberOfReplicas,PVC:.status.kubernetesStatus.pvcName,NS:.status.kubernetesStatus.namespace --no-headers
