#!/bin/bash -eu

if [ -n "$NS" ]; then
    NS=$(gum spin --title "Fetching namespaces..." --show-output -- kubectl get namespace -o custom-columns=NAME:.metadata.name --no-headers | gum filter --placeholder="Select namespace...")
fi

kubectl apply -f - << EOF
apiVersion: core.libre.sh/v1alpha1
kind: Bucket
metadata:
  name: dumps
  namespace: $NS
spec:
  provider: cold
  bucketName: $NS-dumps
  purge: false
  policy:
    preset: private
EOF

kubectl wait --for=condition=ready -n $NS buckets/dumps

bucket_secret=$(kubectl get secret -n $NS dumps.bucket.libre.sh -o jsonpath='{.data}')

kubectl apply -f - <<EOF
apiVersion: v1
kind: Secret
metadata:
  name: postgres-pod-config
  namespace: $NS
type: Opaque
stringData:
  AWS_ACCESS_KEY_ID: $(echo $bucket_secret | jq -r '.accessKey' | base64 -d)
  AWS_SECRET_ACCESS_KEY: $(echo $bucket_secret | jq -r '.secretKey' | base64 -d)
  AWS_S3_FORCE_PATH_STYLE: "true"
  WAL_S3_BUCKET: $(echo $bucket_secret | jq -r '.bucket' | base64 -d)
  AWS_ENDPOINT: $(echo $bucket_secret | jq -r '.url' | base64 -d)
  WAL_S3_ENDPOINT: $(echo $bucket_secret | jq -r '.url' | base64 -d)
  AWS_REGION: default
  USE_WALE: "true"
  USE_WALG_BACKUP: "true"
  WALG_DISABLE_S3_SSE: "true"
EOF
