#!/bin/bash

function last_modified_file_epoch() {
  mc ls --json $1 > /tmp/last_modified_file_epoch.json
  if [ -s /tmp/last_modified_file_epoch.json ]; then
    date -d `jq -s -r '. | sort_by(.lastModified) | reverse [0].lastModified' /tmp/last_modified_file_epoch.json` '+%s'
  else
    echo 0 # file is empty
  fi
}

for NS in `kubectl get ns --no-headers -o custom-columns=":metadata.name"`; do
  for PG in `kubectl -n ${NS} get pg --no-headers -o custom-columns=":metadata.name"`; do
    echo $NS $PG basebackup $(last_modified_file_epoch cold/${NS}-dumps/spilo/${NS}-${PG}/wal/basebackups_005)
    echo $NS $PG wal $(last_modified_file_epoch cold/${NS}-dumps/spilo/${NS}-${PG}/wal/wal_005)
    echo $NS $PG logical_backup $(last_modified_file_epoch cold/${NS}-dumps/spilo/${PG}/nextcloud/logical_backups)
  done
  for MONGO in `kubectl -n ${NS} get perconaservermongodbs.psmdb.percona.com --no-headers -o custom-columns=":metadata.name"`; do
    echo $NS $MONGO mongodump $(last_modified_file_epoch cold/${NS}-dumps/mongodb/)
  done
done
