#!/usr/bin/python

USAGE = '''
Usage:
  convert_label_to_autoreload.py <label or file_with_list_of_labels>
'''

import os
import os.path
import re
import sys
import p4lock
import p4unlock
import sdputils

if len(sys.argv) > 1:
  SDP_INSTANCE = str(sys.argv[1])
else:
  SDP_INSTANCE = '1'

utils = sdputils.SDPUtils(SDP_INSTANCE)
p4 = utils.p4
utils.login()

def check_auto(label, auto):
  for line in os.popen('%s label -o %s' % (p4, label)).readlines():
  if re.search("^Revision:", line):
    auto = 1
  if re.search(" autoreload", line):
    auto = 1
  return(auto)

def droplabellines(labelname):
  input = open('%s.labelfiles.tmp' % (labelname), 'r')
  output = open('%s.labelfiles' % (labelname), 'w')

  for line in input.readlines():
  line = line.rstrip()
  def rep(mo): return mo.group(1)
  line = re.sub(r'(#\d+) - .*', rep, line)
  output.write(line + '\n')

  input.close()
  output.close()
  os.remove('%s.labelfiles.tmp' % (labelname))

def convertlabel(label):
  auto = 0
  auto = check_auto(label, auto)
  if auto:
    return()
  
  # The next two lines are replacing any illegal file name characters with
  # and exclamation point and the hex value of the replaced character.
  def rep(mo): return '_%s' % hex(ord(mo.group(0)))[-2:]
  labelfile = re.sub(r'[\@=`~+<>/:\|\\ ,\(\)\[\]\$%^&?;{}\'\"]', rep, label)
  os.system('%s label -o "%s" | sed s/noautoreload/autoreload/ > %s.labelspec' % (p4, label, labelfile))
  os.system('%s files "@%s" > %s.labelfiles.tmp' % (p4, label, labelfile))
  droplabellines(labelfile)
  if (os.path.isfile('%s.labelspec' % (labelfile)) and os.path.isfile('%s.labelfiles' % (labelfile))):
    os.system('%s label -f -d "%s"' % (p4, label))
    os.system('%s label -i < %s.labelspec' % (p4, labelfile))
    p4unlock.unlock(label)
    os.system('%s -x %s.labelfiles labelsync -l "%s"' % (p4, labelfile, label))
    p4lock.lock(label)
    os.remove('%s.labelspec' % (labelfile))
    os.remove('%s.labelfiles' % (labelfile))

###############################################################################
# main
if __name__ == '__main__':
  if len (sys.argv) < 2:
  print USAGE
  sys.exit (1)

  try:
  labellistfile = open( sys.argv[1], "r" )
  for line in labellistfile.readlines():
    line = line.strip()
    if line:
    convertlabel(sys.argv[1].rstrip())
  labellistfile.close()
  except:
  print "No file " + sys.argv[1] + " available, assuming it is the actual label name"
  convertlabel(sys.argv[1].rstrip())

