%%bash
apt-get update
apt-get install -y libffi-dev libssl-dev python-dev python-pip python-imaging python-gdal
pip install cryptography google-api-python-client earthengine-api

"""
Explanation: Earth Engine Datalab Initialization
This notebook demonstrates how to configure a new Google Cloud Datalab instance for use with Earth Engine. You should only need to do this once when you first configure your instance.
1. Install Earth Engine SDK and related libraries
First we install a variety of required and useful libraries, including the Earth Engine SDK itself. This may take a couple of mintues, and will generate lots of output which you can usually ignore.
End of explanation
"""


import ee
import errno
import IPython
import json
import os
import urllib
import urllib2

"""
Explanation: 2. Authorize access to the Earth Engine API
This walks through the same flow that is used by the "earthengine authenticate" command, but it works even when you do not have easy access to an interactive shell on the remote host.  These should become available as helper functions in the Earth Engine client library, but for now you can still do it by hand.
Start by importing the Python libraries that we're going to use to configure the Earth Engine credentials.
End of explanation
"""


def get_authorization_url():
  # This redirect_uri prompts you to copy and paste a code after successful authorization.
  return 'https://accounts.google.com/o/oauth2/auth?' + urllib.urlencode({
      'client_id': ee.oauthinfo.OAuthInfo.CLIENT_ID,
      'scope': ee.oauthinfo.OAuthInfo.SCOPE,
      'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob',
      'response_type': 'code',
  })
  
def get_refresh_token(auth_code):
  args = {
    'code': auth_code,
    'client_id': ee.oauthinfo.OAuthInfo.CLIENT_ID,
    'client_secret': ee.oauthinfo.OAuthInfo.CLIENT_SECRET,
    'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob',
    'grant_type': 'authorization_code',
  }
  response = urllib2.urlopen('https://accounts.google.com/o/oauth2/token',
                             urllib.urlencode(args)).read()
  return json.loads(response)['refresh_token']

def save_token(refresh_token):
  credentials_path = ee.oauthinfo.OAuthInfo.credentials_path()
  try:
    os.makedirs(os.path.dirname(credentials_path))
  except OSError, e:
    if e.errno != errno.EEXIST:
      raise
  json.dump({'refresh_token': refresh_token}, open(credentials_path, 'w'))
  print 'Successfully saved authorization to %s' % credentials_path

"""
Explanation: These helper functions implement the authentication flow.
End of explanation
"""


print(get_authorization_url())

"""
Explanation: Running this next command will print a URL that you can click on to begin the authentication flow.  Copy the code that it generates and come back here for the next step.
End of explanation
"""


save_token(get_refresh_token('https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fearthengine+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdevstorage.read_write&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&response_type=code&client_id=517222506229-vsmmajv00ul0bs7p89v5m89qs8eb9359.apps.googleusercontent.com'))

"""
Explanation: Finally, paste the auth code that you were given into this next command (in place of  "YOUR_AUTH_TOKEN_GOES_HERE") and run it to save your credentials on this Datalab instance.
End of explanation
"""


ee.Initialize()
srtm = ee.Image('USGS/SRTMGL1_003')
srtm_vis = srtm.visualize(min=0, max=5000, gamma=1.6)
srtm_thumb = ee.data.getThumbnail({'image':srtm_vis.serialize()})
IPython.display.display(IPython.display.Image(srtm_thumb))

!ls

"""
Explanation: 3. Take it for a spin
Finally, test out our new credentials by doing something with Earth Engine. This should display a simple thumbnail of global SRTM terrain data.
End of explanation
"""


