#!/bin/bash

#
# This script uploads a file to Iris
#
# This script is tested to work under cygwin bash on windows too
#

if [ $# != 6 ]
then
  echo "IRIS Wrong number of arguments"
  echo "Usage:"
  echo "    $0  ClientId  UserType:UserName  Password  Datacenter  FileName  AssetName"
  echo "Example:"
  echo "    $0  2204:58739:0.0.1:ios:appstore  game:surv_gs_user  password  mdc  gamedb.zip  gamedb_asset" 
  exit 0
fi

# GameLoft ClientId for the game
CLIENT_ID=$1

# Credentials
USERNAME=$2
PASSWORD=$3
SCOPE="auth asset asset_upload"

#GameLoft Datacenter
DATACENTER=$4

# Files to upload
SRC_FILE=$5

# Assigned asset name in Iris
ASSET_NAME=$6

# Servers
EVE_URL=http://eve.gameloft.com:20001
# Get Pandora URL from EVE
PANDORA_URL=`curl -s $EVE_URL/config/$CLIENT_ID/datacenters/$DATACENTER/urls | sed 's/\,/,\'$'\n/g' | grep "pandora" | cut -d '"' -f 4`
# Translate/redirect beta/gold address to the beta or gold master address to ensure it can work and it will be replicated to all DCs
# Note: .com -> .org  (http://palantir.gameloft.org/master_fed.html)
PANDORA_URL=`echo $PANDORA_URL | sed 's/vbeta\.gameloft\.com/vbeta-master\.gameloft\.org/' | sed 's/vgold\....\.gameloft\.com/vgold-master\.gameloft\.org/'`
# Get Janus and Iris URLs from Pandora
AUTH_URL=`curl -s $PANDORA_URL/locate/auth`
ASSET_URL=`curl -s $PANDORA_URL/locate/asset`

# Authorize and get access-token
ACCESS_TOKEN=`curl -k -s -d '' https://$AUTH_URL/authorize -d "username=$USERNAME&password=$PASSWORD&scope=$SCOPE&client_id=$CLIENT_ID" | cut -d '"' -f 4`

echo
echo "Uploading $SRC_FILE to Iris"
echo
echo "  Client ID:    $CLIENT_ID"
echo "  Data Center:  $DATACENTER"
echo "  Username:     $USERNAME"
echo "  File Name:    $SRC_FILE"
echo "  Asset Name:   $ASSET_NAME"
echo "  Eve:          $EVE_URL"
echo "  Pandora:      $PANDORA_URL"
echo "  Janus:        $AUTH_URL"
echo "  Iris:         $ASSET_URL"
echo "  Access token: $ACCESS_TOKEN"
echo
 
echo
echo "Server response:"
echo
curl -k -s -F "data=@$SRC_FILE" -F "access_token=$ACCESS_TOKEN" -F "only_this_client=True" -F "override=True" https://$ASSET_URL/assets/$CLIENT_ID/$ASSET_NAME
echo
echo


