1#!/usr/bin/env python
2# Copyright 2017 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Updates the Fuchsia SDK to the given revision. Should be used in a 'hooks_os'
7entry so that it only runs when .gclient's target_os includes 'fuchsia'."""
8
9import os
10import shutil
11import subprocess
12import sys
13import tarfile
14import tempfile
15
16REPOSITORY_ROOT = os.path.abspath(os.path.join(
17    os.path.dirname(__file__), '..', '..'))
18sys.path.append(os.path.join(REPOSITORY_ROOT, 'build'))
19
20import find_depot_tools
21
22
23def EnsureDirExists(path):
24  if not os.path.exists(path):
25    print 'Creating directory %s' % path
26    os.makedirs(path)
27
28
29def main():
30  if len(sys.argv) != 2:
31    print >>sys.stderr, 'usage: %s <sdk_hash>' % sys.argv[0]
32    return 1
33
34  sdk_hash = sys.argv[1]
35  output_dir = os.path.join(REPOSITORY_ROOT, 'third_party', 'fuchsia-sdk')
36
37  hash_filename = os.path.join(output_dir, '.hash')
38  if os.path.exists(hash_filename):
39    with open(hash_filename, 'r') as f:
40      if f.read().strip() == sdk_hash:
41        # Nothing to do.
42        return 0
43
44  print 'Downloading SDK %s...' % sdk_hash
45
46  if os.path.isdir(output_dir):
47    shutil.rmtree(output_dir)
48
49  bucket = 'gs://fuchsia-build/fuchsia/sdk/linux64/'
50  with tempfile.NamedTemporaryFile() as f:
51    cmd = [os.path.join(find_depot_tools.DEPOT_TOOLS_PATH, 'gsutil.py'),
52           'cp', bucket + sdk_hash, f.name]
53    subprocess.check_call(cmd)
54    f.seek(0)
55    EnsureDirExists(output_dir)
56    tarfile.open(mode='r:gz', fileobj=f).extractall(path=output_dir)
57
58  with open(hash_filename, 'w') as f:
59    f.write(sdk_hash)
60
61  return 0
62
63
64if __name__ == '__main__':
65  sys.exit(main())
66