#!/usr/bin/env python

# Copyright 2016 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import hashlib
import os
import shutil
import stat
import sys
import urllib2

os.chdir(os.path.join(os.path.dirname(__file__), os.pardir))

dst = 'bin/gn.exe' if 'win32' in sys.platform else 'bin/gn'

sha1 = '2f27ff0b6118e5886df976da5effa6003d19d1ce' if 'linux'  in sys.platform else \
       '9be792dd9010ce303a9c3a497a67bcc5ac8c7666' if 'darwin' in sys.platform else \
       'eb69be2d984b4df60a8c21f598135991f0ad1742'  # Windows

def sha1_of_file(path):
  h = hashlib.sha1()
  if os.path.isfile(path):
    with open(path, 'rb') as f:
      h.update(f.read())
  return h.hexdigest()

if sha1_of_file(dst) != sha1:
  with open(dst, 'wb') as f:
    f.write(urllib2.urlopen('https://chromium-gn.storage-download.googleapis.com/' + sha1).read())

  os.chmod(dst, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR |
                stat.S_IRGRP                | stat.S_IXGRP |
                stat.S_IROTH                | stat.S_IXOTH )

# We'll also copy to a path that depot_tools' GN wrapper will expect to find the binary.
copy_path = 'buildtools/linux64/gn' if 'linux'  in sys.platform else \
            'buildtools/mac/gn'     if 'darwin' in sys.platform else \
            'buildtools/win/gn.exe'
if os.path.isdir(os.path.dirname(copy_path)):
  shutil.copy(dst, copy_path)