apiVersion: v1
kind: ConfigMap
metadata:
  name: rsync-config
data:
  run-rsync.sh: |-
    #!/bin/sh
    set -eu
    echo "Starting rsync..."

    no_change_count=0

    while [ "$no_change_count" -lt 3 ]; do
      # use the i flag to get per line output of each change
      rsync_output=$(rsync -avzi --delete /local-data/ /persistent-data/)
      # echo "$rsync_output"

      # in this format rsync outputs at least 4 lines:
      # ---
      # sending incremental file list
      #
      # sent 145,483 bytes  received 717 bytes  26,581.82 bytes/sec
      # total size is 708,682,765  speedup is 4,847.35
      # ---
      # even though a non-zero number of bytes is sent, no changes were made

      line_count=$(echo "$rsync_output" | wc -l)

      if [ "$line_count" -eq 4 ]; then
        echo "Rsync output was: $rsync_output"
        no_change_count=$((no_change_count + 1))
        echo "No changes detected. Incrementing no_change_count to $no_change_count."
      else
        no_change_count=0
        echo "Changes detected. Resetting no_change_count to 0."
      fi

      echo "Rsync completed. Sleeping for 10 minutes..."
      sleep 600
    done

    echo "No changes detected for 3 consecutive runs. Exiting."