#!/usr/bin/python3
import os, sys, shutil, collections
from optparse import OptionParser

# Fix for python 2
try:
  input = raw_input
except NameError:
  pass

def find_recursive(root, subpath, maxdepth=4):
  queue = collections.deque([(root, 0)])
  if 'PATH' in os.environ:
    envpath = os.environ['PATH'].split(':')
    relpath = ['..'] * (len(subpath) - 1)
    queue.extendleft([(os.path.join(x, *relpath), maxdepth) for x in envpath if 'android' in x.lower()])
  while len(queue) > 0:
    item = queue.popleft()
    if os.path.isfile(os.path.join(item[0], *subpath)):
      return os.path.abspath(item[0])
    if item[1] < maxdepth:
      for name in os.listdir(item[0]):
        fullname = os.path.join(item[0], name)
        if os.path.isdir(fullname) and '.' not in name:
          queue.append((fullname, item[1] + 1))
  return None

def read_local_properties():
  androidRoot = os.path.join(os.path.dirname(sys.argv[0]), '..', '..', 'android')
  propsFile = os.path.join(androidRoot, 'local.properties')
  sdkDir = None
  if os.path.exists(propsFile):
    with open(propsFile, 'r') as f:
      for line in f:
        line = line.strip()
        if line.startswith('sdk.dir') and '=' in line:
          sdkDir = line.split('=')[1].strip()
  return sdkDir

def test_path(title, path, subpath):
  test = os.path.join(path, *subpath)
  if path and os.path.isfile(test):
    return os.path.abspath(path)
  print('Could not find "{0}", it\'s not an {1} path!'.format(test, title))
  return None

def query_path(title, option, default, subpath):
  if option:
    path = test_path(title, option, subpath)
    if path:
      return path
  default = '' if not default else os.path.abspath(default)
  searchHint = ', "s" to search'
  while True:
    path = input('Path to {0}{1} [{2}]:'.format(title, searchHint, default)) or default
    if len(searchHint) > 0 and path.lower().strip() == 's':
      found = find_recursive(os.path.expanduser('~'), subpath)
      if found:
        print('Found {0} at "{1}".'.format(title, found))
        default = found
      else:
        print('{0} not found.'.format(title))
      searchHint = ''
    else:
      break
  return test_path(title, path, subpath)

def write_local_properties(sdkDir):
  sdkProp = 'sdk.dir={0}'.format(sdkDir)
  content = ''.join([x + '\n' for x in [
      '# Autogenerated file',
      '# Do not add it to version control',
      sdkProp,
  ]])

  # Create android/local.properties
  androidRoot = os.path.join(os.path.dirname(sys.argv[0]), '..', '..', 'android')
  propsFile = os.path.abspath(os.path.join(androidRoot, 'local.properties'))
  print('Writing "{0}" to {1}'.format(sdkProp, propsFile))
  with open(propsFile, 'w') as f:
    f.write(content)

if __name__ == '__main__':
  parser = OptionParser()
  parser.set_description(' '.join([
    'Writes Android SDK location into android/local.properties file.',
    'Prompts for SDK location and offers to search for it if started without options.',
  ]))
  parser.add_option('-s', '--sdk', help='path to Android SDK')
  options, _ = parser.parse_args()

  sdkDirOld = read_local_properties()
  sdkDir = query_path('Android SDK', options.sdk, sdkDirOld, ['platform-tools', 'adb'])

  if sdkDir:
    write_local_properties(sdkDir)
