#!/bin/bash -eu

source /root/domains/common/scripts/functions.sh

export S3_COLD_ENDPOINT=https://cold-objects.liiib.re
export STORAGE_CLASS=cold

for NS in `kubectl get ns --no-headers -o custom-columns=":metadata.name" | grep -v "liiib\|soci\|licoo"`; do
  # If secret for dump s3 bucket doesn't exists, skip this NS
  if ! kubectl -n ${NS} get secret ${NS}-dumps 2>/dev/null; then
    continue
  fi

  echo "Working on NS: $NS"

  # Backup old dump secret
  kubectl -n ${NS} get secret ${NS}-dumps --export -o yaml 2> /dev/null | sed "s/${NS}-dumps/${NS}-dumps-backup/g" | kubectl -n ${NS} apply -f -
  kubectl -n ${NS} delete secret ${NS}-dumps

  # Create new cold dumps bucket
  export AWS_ACCESS_KEY_ID=${NS}-dumps
  export SECRET_NAME=${NS}-dumps
  create_bucket

  # If a PG is Running
  if kubectl -n ${NS} get pg --no-headers | grep ${NS} | grep -q Running; then
    # Update dump cronjob
    export CJ=`kubectl -n $NS get cj --no-headers -o custom-columns=":metadata.name" | grep dump`
    kubectl -n ${NS} set env cj/$CJ LOGICAL_BACKUP_S3_ENDPOINT=${S3_COLD_ENDPOINT}

    # Patch pg config map
    export PG_CLUSTER=`kubectl -n ${NS} get pg --no-headers -o custom-columns=":metadata.name" | grep ${NS}`
    export ARCHIVE_MODE=off
    pg_set_archive_mode_and_wait
    kubectl -n ${NS} patch  --type merge cm postgres-pod-config --patch '{"data":{"AWS_ACCESS_KEY_ID":"'${AWS_ACCESS_KEY_ID}'"}}'
    kubectl -n ${NS} patch  --type merge cm postgres-pod-config --patch '{"data":{"AWS_SECRET_ACCESS_KEY":"'${AWS_SECRET_ACCESS_KEY}'"}}'
    kubectl -n ${NS} patch  --type merge cm postgres-pod-config --patch '{"data":{"AWS_ENDPOINT":"'${S3_COLD_ENDPOINT}'"}}'
    kubectl -n ${NS} patch  --type merge cm postgres-pod-config --patch '{"data":{"WAL_S3_ENDPOINT":"'${S3_COLD_ENDPOINT}'"}}'
    export ARCHIVE_MODE=on
    pg_set_archive_mode_and_wait
  else
    echo "No PG in Running state"
  fi

  # If a Mongo is Ready
  if kubectl -n ${NS} get perconaservermongodbs.psmdb.percona.com --no-headers | grep -q ready; then
    # Patch mongo
    MONGO=`kubectl -n ${NS} get perconaservermongodbs.psmdb.percona.com --no-headers -o custom-columns=":metadata.name"`
    kubectl -n ${NS} patch  --type merge perconaservermongodbs.psmdb.percona.com ${MONGO} --patch '{"spec":{"backup":{"storages":{"backup":{"s3":{"endpointUrl":"'${S3_COLD_ENDPOINT}'"}}}}}}'
  fi
done
