#!/bin/bash

initUser() {
  /bin/frostfs-s3-authmate register-user \
    --wallet $WALLET_PATH \
    --rpc-endpoint http://morph-chain.frostfs.devenv:30333 \
    --username $USERNAME \
    --contract-wallet /wallet.json 1> /dev/null && touch $WALLET_CACHE/$USERNAME
}

issueCreds() {
  /bin/frostfs-s3-authmate issue-secret \
    --wallet $WALLET_PATH \
    --peer s01.frostfs.devenv:8080 \
    --gate-public-key $S3_GATE_PUBLIC_KEY \
    --container-placement-policy "REP 3"
}

set -e

WALLET_PATH=/wallets/$2
if [[ -z "$2" ]]; then
  WALLET_PATH=/wallets/wallet.json
fi

S3_GATE_PUBLIC_KEY=$3
if [[ -z "$3" ]]; then
  S3_GATE_PUBLIC_KEY=0313b1ac3a8076e155a7e797b24f0b650cccad5941ea59d7cfd51a024a8b2a06bf
fi 

WALLET_CACHE=/data/wallets
mkdir -p $WALLET_CACHE

USERNAME=$(echo $WALLET_PATH | md5sum | cut -d' ' -f1)
if [ ! -e $WALLET_CACHE/$USERNAME ]; then
  initUser
fi

if [ $1 == "s3" ]; then
  issueCreds
fi