#!/bin/bash


function usage
{
  echo ""
  echo "Usage:"
  echo ""
  echo "  $0 ['--suffix' suffix] credential 'create'|'get'|'set'|'clear'|'reset'|'modify' options"
  echo ""
  echo "     '--suffix' suffix - optional _savegame suffix to append, eg: '_hq' "
  echo ""
  echo "     credential        - the device identifier such as:  iphone:2345efggsesdfv=="
  echo ""
  echo "        'create' password       - will create a new profile using the given password"
  echo "        'clear'                 - will clear all data in seshat associated with that profile (ignores suffix)"
  echo "        'reset'                 - will reset the profile to a default empty savegame state"
  echo "        'get' options           - get data from profile, options are one of 'all'|'savegame'|'layout'|'level'|'name'|'resources'"
  echo "           'all'                           - will get all data in seshat associated with that profile (ignores suffix)"
  echo "           'savegame'                      - will get all the savegame data associated with the profile (using suffix)"
  echo "           'layout'                        - buildings and debris"
  echo "           'level'                         - level of the player"
  echo "           'name'                          - the player's name"
  echo "           'resources'                     - resource levels of the player"
  echo "        'set' path file         - will set in profile under path selector with the data from file (ignores suffix)"
  echo "        'set_string' path str   - will set in profile under path selector with str (ignores suffix)"
  echo "        'modify' options        - modifies the profile, options are one of 'layout'|'level'|'name'|'resources'"
  echo "           'layout'    layout.json         - layout.json is a file containing a level"
  echo "           'level'     level               - level is a number of the level to set the player to"
  echo "           'name'      name                - a string to set the player name to"
  echo "           'resources' hc,food,fuel,scrap  - 4 comma seperated numbers for the resource levels"
  echo ""
  exit -1
}


#
# SaveGame suffix, eg: setting to IN will change in the profile _savegameIN
#
SG_SUFFIX=""


# . ./_config.sh
USERNAME=surv_gs_user
PASSWORD=password
CLIENTID=2204:58739:0.0.5i:ios:appstore

DATACENTER=mdc
EVE_URL=http://eve.gameloft.com:20001
CLIENTID_URLENCODED='2204%3A58739%3A0%2E0%2E2%3Aios%3Aappstore'
PANDORA_URL=`curl -s $EVE_URL/config/$CLIENTID_URLENCODED/datacenters/$DATACENTER/urls | tr ',' '\n' | grep pandora | cut -d ':' -f 2- | sed -e 's/^."//'  -e 's/"$//'`


if [ "$1" == "--suffix" ]
then
  SG_SUFFIX="$2"
  shift
  shift
fi


function check_arg_count
{
  # Check enough arguments
  if [ "$1" != "$2" ]
  then
    usage
  fi
}


function login_and_echo_token
{
  SCOPE="auth storage storage_restricted storage_admin"
  JANUS_URL="https://$(curl -s $PANDORA_URL/locate/auth)"
  curl -s -d '' "$JANUS_URL/authorize" --data-urlencode "access_token_only" --data-urlencode "client_id=$CLIENTID" --data-urlencode "username=$1" --data-urlencode "password=$2" --data-urlencode "scope=$SCOPE"
}


function print_resources
{
  echo "Hard Currency: $1"
  echo "Food:          $2"
  echo "Fuel:          $3"
  echo "Scrap:         $4"
}


# Could add a while look, and shift arguments to make multiple operations possible

# Check operation is valid
case $2 in 
  'create') check_arg_count "$#" "3" ;;
  'get')    check_arg_count "$#" "3" ;;
  'set')    check_arg_count "$#" "4" ;;
  'set_string') check_arg_count "$#" "4" ;;
  'clear')  check_arg_count "$#" "2" ;;
  'reset')  check_arg_count "$#" "2" ;;
  'modify') check_arg_count "$#" "4" ;;
  *)
    usage
    ;;
esac


STORAGE_URL="https://$(curl -s $PANDORA_URL/locate/storage)"


case $2 in 
  'create')
      TOKEN=`login_and_echo_token "$1" "$3"`
      #echo "Token is \"$TOKEN\""
      CREATION_DATE=`date "+%Y-%m-%d %H:%M:%S"`
      # BLANK_PROFILE="{ \"created\": \"${CREATION_DATE}Z\", \"credential\": \"$1\", \"current_client_id\": \"$CLIENTID\" }"
      # curl -d "" "$STORAGE_URL/profiles/$1/myprofile" --data-urlencode "access_token=$TOKEN" --data-urlencode "object=$BLANK_PROFILE"
      curl -d "" "$STORAGE_URL/profiles/$1/myprofile" --data-urlencode "access_token=$TOKEN" --data-urlencode "object={ }"
      echo "Don't forget to reset the profile first, then populate with save game data"
      exit 0
      ;;
  'get')
      TOKEN=`login_and_echo_token "game:${USERNAME}" "${PASSWORD}"`
      #echo "Token is \"$TOKEN\""
      case $3 in
        'all')
            curl -G -s "$STORAGE_URL/profiles/$1/myprofile" --data-urlencode "access_token=$TOKEN"
            ;;
        'savegame')
            # echo "Getting save game"
            curl -G -s "$STORAGE_URL/profiles/$1/myprofile/_savegame${SG_SUFFIX}" --data-urlencode "access_token=$TOKEN"
            ;;
        'layout')
            echo "Getting layout:"
            curl -G -s "$STORAGE_URL/profiles/$1/myprofile/_savegame${SG_SUFFIX}.data.progress.buildings" --data-urlencode "access_token=$TOKEN"
            curl -G -s "$STORAGE_URL/profiles/$1/myprofile/_savegame${SG_SUFFIX}.data.progress.debris" --data-urlencode "access_token=$TOKEN"
            ;;
        'level')
            echo "Getting player level"
            echo "<br>"
            echo "Progess level:"
            curl -G -s "$STORAGE_URL/profiles/$1/myprofile/_savegame${SG_SUFFIX}.data.progress.lvl" --data-urlencode "access_token=$TOKEN"
            echo "<br>"
            echo "Matching level:"
            curl -G -s "$STORAGE_URL/profiles/$1/myprofile/_savegame${SG_SUFFIX}.data.social.me.matching" --data-urlencode "access_token=$TOKEN"
            ;;
        'name')
            curl -G -s "$STORAGE_URL/profiles/$1/myprofile/_savegame${SG_SUFFIX}.data.social.me.name" --data-urlencode "access_token=$TOKEN"
            ;;
        'resources')
            RESOURCES_JSON=`curl -G -s "$STORAGE_URL/profiles/$1/myprofile/_savegame${SG_SUFFIX}.data.progress.inventory.rc.balance" --data-urlencode "access_token=$TOKEN"`
	    print_resources `echo $RESOURCES_JSON | tr ',' '\n' | grep "amount" | cut -d ':' -f 2 | tr '\n' ' '`
            ;;
        *)
            usage
            ;;
      esac
      ;;
  'set')
      TOKEN=`login_and_echo_token "game:${USERNAME}" "${PASSWORD}"`
      #echo "Token is \"$TOKEN\""
      echo "Setting value on profile"
      TMP_SET_PROFILE=`mktemp -t tmp-profile-reset.XXX`
      PROFILE_NAME=`echo $1 | cut -d ':' -f 2`
      echo "object=" > $TMP_SET_PROFILE
      cat $4 >> $TMP_SET_PROFILE
      # Blat a default profile in to _savegame.data
      curl -d "" "$STORAGE_URL/profiles/$1/myprofile/${3}" --data-urlencode "access_token=$TOKEN" --data-binary @$TMP_SET_PROFILE
      rm $TMP_SET_PROFILE
      ;;
  'set_string')
      TOKEN=`login_and_echo_token "game:${USERNAME}" "${PASSWORD}"`
      #echo "Token is \"$TOKEN\""
      echo "Setting value on profile"
      curl -d "" "$STORAGE_URL/profiles/$1/myprofile" --data-urlencode "access_token=$TOKEN" --data-urlencode "object={ \"$3\" : \"$4\" }" --data-urlencode "operation=batch_set"
      ;;
  'clear')
      TOKEN=`login_and_echo_token "game:${USERNAME}" "${PASSWORD}"`
      #echo "Token is \"$TOKEN\""
      echo "Clearing profile"
      curl -d "" "$STORAGE_URL/profiles/$1/myprofile" --data-urlencode "access_token=$TOKEN" --data-urlencode "object={}"
      ;;
  'reset')
      TOKEN=`login_and_echo_token "game:${USERNAME}" "${PASSWORD}"`
      #echo "Token is \"$TOKEN\""
      echo "Resetting profile"

      TMP_RESET_PROFILE=`mktemp -t tmp-profile-reset.XXX`
      PROFILE_NAME=`echo $1 | cut -d ':' -f 2`
      MATCHTIME=`date +%s`
cat << EOF > $TMP_RESET_PROFILE
object={
  "data": {
    "ads": { "num_ads": 3 }, "defence": { "lvl": 1 }, "map": { "tm_treas": 0, "tm_visit": 1443575970 },
    "progress": { "inventory": { "rc": {
          "balance": [
            { "amount": 1000, "type": 0 },
            { "amount": 50, "type": 1 },
            { "amount": 10, "type": 2 },
            { "amount": 10, "type": 3 },
            { "amount": 0, "type": 4 }
          ] } }, "lvl": 1, "pvp": 1,
      "survivors": [
        { "type": "cha_s_karl_01_01", "uid": 38 },
        { "type": "cha_s_nathalie_01_01", "uid": 39 },
        { "type": "cha_s_lydia_01_01", "uid": 40 },
        { "type": "cha_s_profCharles_01_01", "uid": 41 },
        { "type": "cha_s_sarah_01_01", "uid": 42 }
      ], "trp": 0, "uid": 43, "xp": 0
    }, "social": {
      "country": "au", "loggedInfoFacebook": false, "me": { "matchtime": $MATCHTIME, "credentials": "$1", "matching": 1, "name": "$PROFILE_NAME" }, "receivedWelcomeGift": false
    }, "tutorial": { "TutorialTasks": [
        true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
        true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true
      ] }, "version": 8
  },
  "lock": {
    "is_locked": false,
    "owner": "$1",
    "time": 1443742749
  }
}
EOF

      # Blat a default profile in to _savegame.data
      curl -d "" "$STORAGE_URL/profiles/$1/myprofile/_savegame${SG_SUFFIX}" --data-urlencode "access_token=$TOKEN" --data-binary @$TMP_RESET_PROFILE
      rm $TMP_RESET_PROFILE
      ;;
  'modify')
      TOKEN=`login_and_echo_token "game:${USERNAME}" "${PASSWORD}"`
      #echo "Token is \"$TOKEN\""
      echo "Modifying"
      # echo "Using credential $1"
      case $3 in
        'layout')
            echo "Modifying layout"
            [ -f "$4" ] || usage

            # If need to escape quotes, use this:   | sed 's/"/\\"/g'
            TMP_LAYOUT=`mktemp -t tmp-profile-layout-data.XXX`

            # Setup the buildings
            echo "Setting up the buildings"
            echo "object=" > $TMP_LAYOUT
            # Strip from the input json everything except for "buildings" and insert in uid values
            # Don't change the newlines or whitespace in the next line. Python requires specific whitespace.
            cat "$4" | python -c "import sys, jsoninputData = json.load(sys.stdin)newData = inputData[\"buildings\"]uid=0for b in newData:  b[\"uid\"] = uid  uid = uid + 1print json.dumps(newData)" >> $TMP_LAYOUT
            # Blat in to _savegame.data.progress.buildings
            curl -d "" "$STORAGE_URL/profiles/$1/myprofile/_savegame${SG_SUFFIX}.data.progress.buildings" --data-urlencode "access_token=$TOKEN" --data-binary @$TMP_LAYOUT

            # Setup the debris
            echo "Setting up the debris"
            echo "object=" > $TMP_LAYOUT
            # Strip from the input json everything except for "debris" and insert in uid values
            # Don't change the newlines or whitespace in the next line. Python requires specific whitespace.
            cat "$4" | python -c "import sys, jsoninputData = json.load(sys.stdin)newData = inputData[\"debris\"]uid=0for b in newData:  b[\"uid\"] = uid  uid = uid + 1print json.dumps(newData)" >> $TMP_LAYOUT
            # Blat in to _savegame.data.progress.debris
            curl -d "" "$STORAGE_URL/profiles/$1/myprofile/_savegame${SG_SUFFIX}.data.progress.debris" --data-urlencode "access_token=$TOKEN" --data-binary @$TMP_LAYOUT

            rm $TMP_LAYOUT
            ;;
        'level')
            echo "Modifying player level to $4"
            curl -d "" "$STORAGE_URL/profiles/$1/myprofile/_savegame${SG_SUFFIX}.data.progress.lvl" --data-urlencode "access_token=$TOKEN" --data-urlencode "object=$4"
            curl -d "" "$STORAGE_URL/profiles/$1/myprofile/_savegame${SG_SUFFIX}.data.social.me.matching" --data-urlencode "access_token=$TOKEN" --data-urlencode "object=$4"
            ;;
        'name')
            echo "Modifying player name to $4"
            curl -d "" "$STORAGE_URL/profiles/$1/myprofile/_savegame${SG_SUFFIX}.data.social.me.name" --data-urlencode "access_token=$TOKEN" --data-urlencode "object=\"$4\""
            # curl -d "" "$STORAGE_URL/profiles/$1/myprofile/_savegame${SG_SUFFIX}.data.social.me.credentials" --data-urlencode "access_token=$TOKEN" --data-urlencode "object=\"$1\""
            ;;
        'resources')
            HC=`echo $4 | cut -d ',' -f 1`
            FOOD=`echo $4 | cut -d ',' -f 2`
            FUEL=`echo $4 | cut -d ',' -f 3`
            SCRAP=`echo $4 | cut -d ',' -f 4`
            echo "Modifying resources to   food: $FOOD  fuel: $FUEL  scrap: $SCRAP  hard currency: $HC"
            curl -d "" "$STORAGE_URL/profiles/$1/myprofile/_savegame${SG_SUFFIX}.data.progress.inventory.rc.balance" --data-urlencode "access_token=$TOKEN" --data-urlencode "object=[ { \"amount\": $HC, \"type\": 0 }, { \"amount\": $FOOD, \"type\": 1 }, { \"amount\": $FUEL, \"type\": 2 }, { \"amount\": $SCRAP, \"type\": 3 }, { \"amount\": 0, \"type\": 4 } ]"
            ;;
        *)
            usage
            ;;
      esac
      ;;
esac

echo

