#!/usr/bin/python

"""
This program should lock a perforce label.

The only command line parameter is the label
p4lock.py LABEL
"""

import isitalabel
import os
import re
import sys

def lock (label):
  x = isitalabel.check(label)
  if x == 0:
    print("There is no label %s.") % (label)
    sys.exit(1)
    
  label_pattern = re.compile(r"^Label:\s+.*")
  lock_pattern = re.compile(r"^Options:\s+unlocked")
  
  tempfile = open("temp.txt", "w")
  linelist = []

  # owner.txt is a one line file generated by the p4unlock.py script. It saves
  # the name of the label owner so it can be put back by this script.
  # The owner line is removed by p4unlock.py because Perforce doesn't allow 
  # anyone except the owner of a label to update the label.

  found_owner = True
  if os.path.isfile("owner.txt"):
    ownerfile = open("owner.txt", "r")
    for line in ownerfile.readlines():
      owner = line
    ownerfile.close()
    os.remove("owner.txt")
  else:
    found_owner = False
  
  for line in os.popen("p4 label -o %s" % (label), "r").readlines():
    if found_owner:
      match = label_pattern.match(line)
      if match != None:
        linelist = linelist + ["Owner:\t%s\n" % (owner)]
    line = lock_pattern.sub(r"Options:	locked", line)
    linelist = linelist + [line]

  tempfile.writelines(linelist)
  tempfile.close ()
  os.system("p4 label -i < temp.txt")
  os.remove("temp.txt")

def main():
  if len(sys.argv) < 2:
    print ('Invalid input')
    print ('You must specify a label')
    print ('usage: p4lock.py LABELNAME')
  else:
    label = sys.argv[1]
    lock(label)

###########################################################################
# main
if __name__ == '__main__': 
  main()

