#!/usr/bin/env python

import os
from glob import glob

if __name__ == '__main__':
  #patch meta file created by versioneer
  ver_file = os.path.join(os.environ['SP_DIR'], os.environ['PKG_NAME'], '_version.py')
  assert os.path.isfile(ver_file), "Could not locate meta file created by versioneer!"
  ver_file_data = None
  with open(ver_file) as fi:
    ver_file_data = fi.readlines()
  with open(ver_file, 'w') as fo:
    for line in ver_file_data:
      if '"dirty":' in line:
        fo.write(' "dirty" : false,\n')
      elif '"version":' in line:
        fo.write(' "version": "{}"\n'.format(os.environ['PKG_VERSION']))
      else:
        fo.write(line)
  print('Patched _version.py.')

  #patch the egg-info directory
  egg_dir = glob(os.path.join(os.environ['SP_DIR'], '{}-*.egg-info'.format(os.environ['PKG_NAME'])))
  if len(egg_dir) == 1:
    egg_dir = egg_dir[0]
    old_dir_name = os.path.basename(egg_dir)
    new_dir_name = '{}-{}-py{}.egg-info'.format(os.environ['PKG_NAME'], os.environ['PKG_VERSION'],
                                                os.environ['PY_VER'])
    new_dir_path = os.path.join(os.path.dirname(egg_dir), new_dir_name)
    if old_dir_name != new_dir_name:
      os.rename(egg_dir, new_dir_path)
      print('Renamed egg-info directory.')

    #patch PKG_INFO file inside egg-info directory
    pkg_info = os.path.join(new_dir_path, 'PKG-INFO')
    assert os.path.isfile(pkg_info), "Could not locate PKG-INFO!"
    pkg_info_data = None
    with open(pkg_info) as fi:
      pkg_info_data = fi.readlines()
    with open(pkg_info, 'w') as fo:
      for line in pkg_info_data:
        if line.startswith('Version:'):
          fo.write('Version: {}\n'.format(os.environ['PKG_VERSION']))
        else:
          fo.write(line)
    print('Patched PKG-INFO.')
  else:
    print("Couldn't locate {}'s egg-dir in site-packages!".format(os.environ['PKG_NAME']))
