#!/bin/sh
{ set +x; } 2>/dev/null

usage() {
    echo "usage: $(basename $0) bucket"
    [ "$1" = "-h" ] || [ "$1" = "--help" ]; exit
}

[ "$1" = "-h" ] || [ "$1" = "--help" ] && usage "$@"

[[ $# != 1 ]] && usage

[[ -z $2 ]] && set -- "$1" S3-"$1"-FullAccess
[[ -z "$1" ]] && echo "ERROR: bucket name is empty" 1>&2 && exit 1
# [[ -z "$2" ]] && echo "ERROR: user name is empty" 1>&2 && exit 1

IFS=
BUCKET_NAME="$1"
USER_NAME="$2"
POLICY_NAME="$1"-FullAccess
POLICY_FILE="$(mktemp)" || exit
POLICY_DOCUMENT="file://$POLICY_FILE"

# User Policy Examples:
# https://docs.aws.amazon.com/AmazonS3/latest/dev/example-policies-s3.html#iam-policy-ex0
cat <<EOF > "$POLICY_FILE" || exit
{
   "Version":"2012-10-17",
   "Statement":[
      {
         "Effect":"Allow",
         "Action":[
            "s3:ListBucket",
            "s3:GetBucketLocation"
         ],
         "Resource":"arn:aws:s3:::$BUCKET_NAME"
      },
      {
         "Effect":"Allow",
         "Action":[
            "s3:PutObject",
            "s3:PutObjectAcl",
            "s3:GetObject",
            "s3:GetObjectAcl",
            "s3:DeleteObject"
         ],
         "Resource":"arn:aws:s3:::$BUCKET_NAME/*"
      }
   ]
}
EOF

aws iam list-users | grep -q "\"$USER_NAME\"" || aws iam create-user --user-name "$USER_NAME" 1> /dev/null || exit
# IAM -> Users -> User -> Permissions
aws iam put-user-policy --user-name "$USER_NAME" --policy-name "$POLICY_NAME" --policy-document "$POLICY_DOCUMENT" || exit
# IAM -> Users -> User -> Security credentials
keys="$(aws iam list-access-keys --user-name "$USER_NAME" | grep "AccessKeyId" | awk -F'"' '{print $4}')"
[[ -n "$keys" ]] && while IFS= read key; do
    aws iam delete-access-key --user-name "$USER_NAME" --access-key-id "$key" || exit
done <<< "$keys";:

out="$(aws iam create-access-key --user-name "$USER_NAME")" || exit

AccessKeyId="$(echo "$out" | grep "AccessKeyId" | awk -F'"' '{print $4}')" || exit
SecretAccessKey="$(echo "$out" | grep "SecretAccessKey" | awk -F'"' '{print $4}')" || exit

# https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html
cat <<EOF
# https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html
AWS_STORAGE_BUCKET_NAME="$BUCKET_NAME"
AWS_STORAGE_USER="$USER_NAME"
AWS_ACCESS_KEY_ID="$AccessKeyId"
AWS_SECRET_ACCESS_KEY="$SecretAccessKey"
EOF

