#!/usr/bin/env python
"""
This script will delete clients and associated shelves listed in delete_clients.txt
"""
import os
import re
import sys
import string
import accessdates
import platform
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()
cfgweeks = int(utils.get('weeks'))

###############################################################################
def delete_clients( command, del_command ):
  clients = []

# Read list of clients to be deleted.
  if os.path.isfile("delete_clients.txt"):
    clientsfile = open( "delete_clients.txt", "r" )

    for client in clientsfile.readlines():
      client = client.rstrip()
      # Avoid deleting or affecting Swarm clients.
      if (re.match ('^swarm-', client)):
        continue
      # Delete shelves from client
      os.system('%s -Ztag changes -s shelved -c %s > shelved.txt' % (p4, client))
      if os.path.isfile("shelved.txt"):
        shelvedfile = open("shelved.txt", "r")
        for changeline in shelvedfile.readlines():
          if re.search("\.\.\. change ", changeline):
            changenum = changeline[11:]
            changenum = changenum.strip()
            os.system('%s shelve -c %s -df' % (p4, changenum))
        shelvedfile.close()
        os.remove("shelved.txt")
      os.system('%s client -f -d "%s"' % (p4, client))

    clientsfile.close()
  else:
    print("No delete_clients.txt file found.")

###############################################################################
# main
if __name__ == '__main__':
  delete_clients( "clients", "client" )
