#!/bin/bash -eu

function usage() {
  echo "Usage:"
  echo "makeBucketsReadOnly.sh mydomain.org"
}

if [ $# -ne 1 ] # we expect 1 arg
  then
    echo "Please pass only 1 argument."
    usage
    exit 1
fi


echo Faire d abord tourner sur sm1:
echo ~/pierre/scripts/createReadOnlyNSuser.sh ${1}
read -p "Press enter to continue"

export NS=`echo ${1} | sed 's/\./-/g'`
export NAME=`echo ${NS} | cut -d"-" -f1`

echo Procedure à envoyer au contributeurice:
echo export MC_HOST_${NS}=https://AWS_ACCESS_KEY_ID:AWS_SECRET_ACCESS_KEY@minio.k7.inide.host
echo mc ls ${NS}/${NS}-dumps
echo export MC_HOST_${NS}=https://AWS_ACCESS_KEY_ID:AWS_SECRET_ACCESS_KEY@s3.standard.indie.host

for BUCKET_SECRET in ` kubectl -n $NS get secrets | grep s3 | cut -d" " -f1`
do
  for key in `kubectl -n ${NS} get secrets ${BUCKET_SECRET} -o json | jq -r '.data | keys | .[]'`; do
    export $key=`kubectl -n ${NS} get secrets ${BUCKET_SECRET} -o json | jq -r ".data.$key" | base64 -d`
  done
  export MC_HOST_ceph=https://${AWS_ACCESS_KEY_ID}:${AWS_SECRET_ACCESS_KEY}@s3.standard.indie.host
  BUCKET=`echo $BUCKET_SECRET | rev | cut -d"-" -f2- | rev` # removes -s3 at the end of the secret name
  echo mc ls ${NS}/${BUCKET}

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

  mc policy set-json /tmp/readonly.json ceph/$BUCKET || true
done

