#!/bin/bash -eu

NS=$(gum spin --title "Fetching namespaces..." --show-output -- kubectl --context louise-michel get namespace -o custom-columns=NAME:.metadata.name --no-headers | gum filter --placeholder="Select namespace...")
USER=${NS}-backup
PASS=$(openssl rand -base64 32)

gum confirm "Are you sure you want to (re)generate backup credentials for $NS ?"

cat << EOF > /tmp/policy.json
{
  "Version": "2012-10-17",
  "Statement": [
   {
    "Effect": "Allow",
    "Action": [
     "s3:GetObject",
     "s3:ListAllMyBuckets",
     "s3:ListBucket"
    ],
    "Resource": [
     "arn:aws:s3:::$NS-dumps/",
     "arn:aws:s3:::$NS-dumps/*",
     "arn:aws:s3:::*-$NS/",
     "arn:aws:s3:::*-$NS/*"
    ]
   }
  ]
}
EOF

gum spin --title "Creating user" --  bash -c \
    "mc admin user add cold $USER $PASS && mc admin user add hot $USER $PASS"

gum spin --title "Creating policy" -- bash -c \
    "mc admin policy add cold $USER /tmp/policy.json && mc admin policy add hot $USER /tmp/policy.json"

gum spin --title "Setting policy" -- bash -c \
    "mc admin policy set cold $USER user=$USER && mc admin policy set hot $USER user=$USER"

rm /tmp/policy.json

gum style \
    --foreground 212 --border-foreground 212 --border double \
    --align center --margin "1 2" --padding "2 4" \
    "Backup credentials generated !" "" $USER $PASS