Skip to content
Snippets Groups Projects
maap-s3.sh 9.76 KiB
Newer Older
#!/bin/bash
#environment variables
BEARER=""
MAAP_ENV_TYPE=${MAAP_ENV_TYPE}
CLIENT_ID=${CLIENT_ID}
USER_INFO_FILE=/usr/bmap/maap-s3-userinfo.json


#Init the bearer
init() {
    
    #Create file for password and token
    if [[ ! -e $USER_INFO_FILE ]]; then
        touch $USER_INFO_FILE
        # ask the user for information email and password
        read -p 'Your email: ' email
        read -p 'Your password: ' password

        echo 
        
        jq -n --arg email_var $email --arg pwd_var $password --arg token_var null '{"email":$email_var, "password": $pwd_var, "token": $token_var }' > $USER_INFO_FILE
        
        echo "Start retrieving token for authent"
edupin's avatar
edupin committed
        BEARER=$(curl -s -X POST -d "client_id=$CLIENT_ID&username=$email&password=$password&grant_type=password&scope=openid+profile" "https://iam.${MAAP_ENV_TYPE,,}.esa-maap.org/oxauth/restv1/token" -v  2>/dev/null | jq -r '.access_token') 
        
        
        #Check if the bearer is set
        if [ -z "$BEARER" ]
        then
            echo "Token is empty. Please 1)run refresh function and check your password"
            exit 1
        else        
            
            #Set the token in the file
            echo "Bearer is saved for 1 hour : $BEARER"
            jq --arg a "${BEARER}" '.token = $a' $USER_INFO_FILE > "tmp" && mv "tmp" $USER_INFO_FILE
        fi

        
    else
    
        #If one hous is exceeded (duration of the token)
        if [ $(($(date +%s)-$(stat -c "%Y" $USER_INFO_FILE))) -lt 3600 ] 
        then 
            echo "INFO: Token is still valid" 
        else 
            echo "INFO: Token is expired, we generate a new one" 
            email=$(cat $USER_INFO_FILE | jq -r '.email')
            password=$(cat $USER_INFO_FILE | jq -r '.password')
            #Generate a new token
            generate_token
        
        fi
    
        #read the json file to get the email and password
        echo "Read personal user info"
        email=$(cat $USER_INFO_FILE | jq -r '.email')
        password=$(cat $USER_INFO_FILE | jq -r '.password')
        BEARER=$(cat $USER_INFO_FILE | jq -r '.token')
    fi
    
    
    
    #Check if the bearer is set
    if [ -z "$BEARER" ]
    then
edupin's avatar
edupin committed
      echo "Token is empty. Please 1)run refresh function 2)read the log for more info 3)check your password"
      exit 1
    else
      echo "Bearer is ready to be used : $BEARER"
      #jq --arg a "${BEARER}" '.token = $a' $USER_INFO_FILE > "tmp" && mv "tmp" $USER_INFO_FILE
      #Set the variable with the access_token
      export BEARER
    fi

}


#########################
# Delete userinfo file  #
#########################
generate_token() {
    BEARER=$(curl -s -X POST -d "client_id=$CLIENT_ID&username=$email&password=$password&grant_type=password&scope=openid+profile" "https://iam.${MAAP_ENV_TYPE,,}.esa-maap.org/oxauth/restv1/token"  2>/dev/null | jq -r '.access_token') 
      
    echo "Bearer is correctly generated with user and password : $BEARER"
    #Set the token in the file
    jq --arg a "${BEARER}" '.token = $a' $USER_INFO_FILE > "tmp" && mv "tmp" $USER_INFO_FILE
    
}



#########################
# Delete userinfo file  #
#########################
refresh() {
    if [[ -e $USER_INFO_FILE ]]; then
        rm $USER_INFO_FILE
        init
    else
        init
    fi
}

#########################
# Upload the data in S3 #
#########################
upload() {
    
    if [ $# -eq 2 ]
    then      
        sourceFile=$1
        destination=$2
        echo "0- Get an existing or fresh token"
        init
        echo 
        echo "1- Starting retrieving the presigned url for the creation of the file"       
        # xargs trim the result
        LOCATION=$(curl -sI -X PUT -H "Authorization: bearer $BEARER" "https://gravitee-gateway.${MAAP_ENV_TYPE,,}.esa-maap.org/s3/$destination" -v | grep -Fi Location | grep -Po "(?<=Location:)[^,]*" | xargs)
            
        #Check if the location is set
        if [ -z "$LOCATION" ]
        then
          echo "Location is empty. Please 1)run init function for fresh token 2)read the log for more info"
          exit 1
        else
           echo "Location is $LOCATION"  
           LOCATION=${LOCATION%$'\r'}
        fi
        
        
        echo 
        echo "2- Use the presigned url given by the header Location to upload the data"
        echo "2.1- Upload starting"
        curl -v -T $sourceFile "$LOCATION"
    
    else
        echo "ERROR: Arguments numbers are not correct, please read the help"
        display_help
    fi

}

#########################
# Delete a  data in S3 #
#########################
delete() {
    
    if [ $# -eq 1 ]
    then      
        s3file=$1
        echo "0- Get an existing or fresh token"
        init
        echo 
        echo "1- Starting retrieving the presigned url for the delation of the file"       
        # xargs trim the result
        LOCATION=$(curl -sI -X DELETE -H "Authorization: bearer $BEARER" "https://gravitee-gateway.${MAAP_ENV_TYPE,,}.esa-maap.org/s3/$s3file" -v | grep -Fi Location | grep -Po "(?<=Location:)[^,]*" | xargs)
            
        #Check if the location is set
        if [ -z "$LOCATION" ]
        then
          echo "Location is empty. Please 1)run init function for fresh token 2)read the log for more info"
          exit 1
        else
           echo "Location is $LOCATION"  
           LOCATION=${LOCATION%$'\r'}
        fi
        
        
        echo 
        echo "2- Use the presigned url given by the header Location to delete the data"
        echo "2.1- Deletion starting"
        curl -v -X DELETE "$LOCATION"
    
    else
        echo "ERROR: Arguments numbers are not correct, please read the help"
        display_help
    fi

}


#########################
# Download data from S3 #
#########################
download() {
    
    if [ $# -eq 2 ]
    then      
        name=$2
        s3Path=$1
        echo "0- Get an existing or fresh token"
        init
        echo 
        echo "1- Starting retrieving the presigned url for the download of the file"       
        # xargs trim the result
edupin's avatar
edupin committed
        LOCATION=$(curl -sI -X GET -H "Authorization: bearer $BEARER" "https://gravitee-gateway.${MAAP_ENV_TYPE,,}.esa-maap.org/s3/$s3Path" | grep -Fi Location | grep -Po "(?<=Location:)[^,]*" | xargs)
        
        echo $LOCATION
        #Check if the location is set
        if [ -z "$LOCATION" ]
        then
          echo
          echo "Location is empty. Please 1)run init function for fresh token 2)read the log for more info"
          exit 1
        else
           echo "Location used to download the file is $LOCATION"  
           LOCATION=${LOCATION%$'\r'}
        fi
        
        
        echo 
        echo "2- Use the presigned url given by the header Location to download the data"
        echo "2.1- Download starting"
        curl -o $name "$LOCATION"
    
    else
        echo "ERROR: Arguments numbers are not correct, please read the help"
        display_help
    fi

}


#########################
# List  data in S3      #
#########################
list() {


    if [ $# -eq 1 ]
    then      
        sourceFile=$1
        destination=$2
        echo "0- Get an existing or fresh token"
        init
        echo 
        echo "1- List all files in folder $sourceFile"              
        curl -s -X GET -H "Authorization: bearer $BEARER" "https://gravitee-gateway.${MAAP_ENV_TYPE,,}.esa-maap.org/s3/$sourceFile?list=true"

    else
        echo "ERROR: Arguments numbers are not correct, please read the help"
        display_help
    fi    

}








#########################
# The command line help #
#########################
display_help() {
edupin's avatar
edupin committed
    echo "Usage: $0 [option...] {init|refresh|upload|download|ls|delete}" >&2
    echo
    echo "   init                                                 Get a fresh token before any request. It ask for email and password"
    echo "   upload   myFile.tiff           path/myFile.tiff      Upload data in the S3"
    echo "   download path/in/S3/file.tiff  myFile.tiff           Download a data from the S3"
    echo "   ls       folder/path                                 List data in a subfolder"
    echo "   delete   path/in/S3/file.tiff                        Delete an existing data on S3"
edupin's avatar
edupin committed
    echo "   refresh                                              Reset credentials and password"
    echo
    # echo some stuff here for the -a or --add-options 
    exit 1
}

################################
# Check if parameters options  #
# are given on the commandline #
################################
while :
do
    case "$1" in
      -r | --resolution)
          if [ $# -ne 0 ]; then
            resolution="$2"   # You may want to check validity of $2
          fi
          shift 2
          ;;
      -h | --help)
          display_help  # Call your function
          exit 0
          ;;
      -d | --display)
          display="$2"
           shift 2
           ;;

      -a | --add-options)
          # do something here call function
          # and write it in your help function display_help()
           shift 2
           ;;

      --) # End of all options
          shift
          break
          ;;
      -*)
          echo "Error: Unknown option: $1" >&2
          ## or call function display_help
          exit 1 
          ;;
      *)  # No more options
          break
          ;;
    esac
done

###################### 
# Check if parameter #
# is set too execute #
######################
case "$1" in
  init)
    init #calling function init()
    ;;
  refresh)
    refresh #calling function refresh()
    ;;    
  upload)
    upload $2 $3 #calling function upload()
    ;;
  ls)
    list $2 # calling function ls()
    ;;
  download)
    download $2 $3 # calling function download()
    ;;
  delete)
    delete $2 $3  # calling function delete()
    ;;
  *)
#    echo "Usage: $0 {init|reset|upload|download|ls|delete}" >&2
     display_help

     exit 1
     ;;
esac