def wipeProj(projPathAtRemote):
    import os, sys, pwd, stat
    from xml.dom import minidom
    from osWalk import walktree
    from userName import userName
    from UnjoinMail import UnjoinMailSub
    from pathInfo import pathInfo_j
    from unjoinProj import unjoinProj
    from snipTree import snipTree

    projPathInfo = pathInfo_j(projPathAtRemote)
    # pathInfo: pathOutput=(pathAbs,projName,projNameA,projNameP,projNameAP,pathPrefix,secId,pidType)
    #                          0       1         2        3         4           5         6    7
    #
    secId = projPathInfo[6]
    pidType = projPathInfo[7]
    projName = projPathInfo[1]
    # give project path (with proj name), relative to pathPrefix as in pathInfo.py
    projNameP = projPathInfo[3]
    pathPrefix = projPathInfo[5]
    if pidType == "private":
        pid = 1
    elif pidType == "shared":
        pid = 3
    else:
        sys.exit("Wrong project type, contact support")
    if secId == "BIOSTAT":
        secIdN = 1
    elif secId == "BIOINFO":
        secIdN = 2
    else:
        sys.exit("Wrong section ID, contact support")

    print "\nYou are going to permanently wipe out a project with the following parameters:"
    print "            Section : %s" % (projPathInfo[6])
    print "       Project Type : %s" % (projPathInfo[7])
    print " Local Project Path : %s" % (projPathInfo[9])
    print "Remote Project Path : %s\n" % (projPathInfo[0])
    pathVerify = raw_input("Is the above information correct [y] (y/n) ? ")
    pathVerify = pathVerify.upper()
    while not (pathVerify in ["", "Y", "N", "YES", "NO"]):
        print 'Please answer with "y" or "n" '
        pathVerify = raw_input("Are these correct [y] (y/n)? ")
        pathVerify = pathVerify.upper()
    if pathVerify in ["N", "NO"]:
        sys.exit("\n")

    # #########################################
    projPathAtRemote = projPathInfo[0]  # os.path.abspath(projPathAtRemote)
    ProjToBeUnjoind = projPathInfo[1]  # projPathAtRemote.split('/')[-1]
    # name of the project to be unjoined
    # #########################################
    while not os.path.exists(projPathAtRemote):
        print "\nThere is no project as your input ('%s'). \nPlease verify the project name and directory path.\n" % (
            projPathAtRemote
        )
        continueDel = raw_input("Do you wan to specify another project to wipe out? y/n: ")
        print "\n"
        if continueDel.strip().upper() == "N":
            sys.exit("Good-bye.\n")
            break
        elif continueDel.strip().upper() != "Y":
            print "Please answer with y or n"
        else:
            projPathAtRemote = raw_input("Please input the name of the project which you want to wipe out: ")
    # #########################################
    if pid in [1, 2]:
        projPathAtLocal = os.environ["HOME"] + "/MyProjects_" + secId + "/private" + "/" + ProjToBeUnjoind
    else:
        projPathAtLocal = os.environ["HOME"] + "/MyProjects_" + secId + "/shared" + "/" + ProjToBeUnjoind
    homePath = os.environ["HOME"]
    os.chdir(os.environ["HOME"])

    #  Initialize as in start.project #####
    startprojectXML = r"//genomics/lib/start.project/start.project.xml"
    BIOINFOprojRootPath = r"//genomics/Projects"
    BIOSTATprojRootPath = r"/proj/BIOSTAT/Projects"
    USERprojRootPathPre = r"MyProjects"
    SHAREDPATH = r"shared"
    PRIVATEPATH = r"private"
    continueAsk = 0
    while continueAsk == 0:
        projExist = "No"
        if not (ProjToBeUnjoind == ""):
            cask = 0
            while cask == 0:
                string1 = "The project contents of '%s' will be purged. Are you sure ?!  y/n: " % (ProjToBeUnjoind)
                AreYouSure = raw_input(string1)
                if AreYouSure.strip().upper() == "Y":
                    print "\nDestorying Project. Please wait... \n ......\n"
                    continueAsk = 1
                    break
                elif AreYouSure.strip().upper() == "N":
                    # print "Good-bye"
                    continueAsk = 1
                    print "\n Good-bye.\n"
                    sys.exit()
                    # break
                else:
                    print "Please answer with y or n"
        else:
            print "\nThere is no project as your input. \nPlease verify the directory path and the project name to be wiped out.\n"  # (\'%s\')%(ProjToBeUnjoindRawInput)
            while True:
                continueDel = raw_input("Do you wan to specify another project to wipe out? y/n: ")
                print "\n"
                if continueDel.strip().upper() == "Y":
                    break
                elif continueDel.strip().upper() == "N":
                    print "Good-bye"
                    continueAsk = 1
                    sys.exit()
                    break
                else:
                    print "Please answer with y or n"
    memberList = []
    if os.path.exists(projPathAtRemote):
        for (basepath, children) in walktree(projPathAtRemote, False):
            for child in children:
                DirFile = os.path.join(basepath, child)
                if os.path.islink(DirFile) and (not os.path.exists(os.path.realpath(DirFile))):  # dead link
                    DirFile = os.path.dirname(os.path.join(basepath, child))
                folderOwner = pwd.getpwuid(os.stat(DirFile)[4])[0]
                if os.environ["USER"] != folderOwner:
                    GidOfjoinProjFolder = os.stat(projPathAtRemote)[5]
                    if GidOfjoinProjFolder in os.getgroups():
                        if (not (oct(os.stat(DirFile)[stat.ST_MODE] & 0777)[2] in ["7", "6", "2", "3"])) or (
                            not (oct(os.stat(DirFile)[stat.ST_MODE] & 0777)[3] in ["7", "6", "2", "3"])
                        ):
                            if not (folderOwner in memberList):
                                print DirFile
                                memberList.append(folderOwner)
                    else:
                        print "%s, which is belong to %s, is not allowed to be deleted." % (
                            DirFile,
                            userName(folderOwner)[1] + userName(folderOwner)[2],
                        )
                        sys.exit()
                elif (oct(os.stat(DirFile)[stat.ST_MODE] & 0777)[2] != "7") or (
                    oct(os.stat(DirFile)[stat.ST_MODE] & 0777)[3] != "7"
                ):
                    unlock = 'chmod ugo=rwx "%s"' % (DirFile)
                    os.system(unlock)

    if len(memberList) >= 1:
        members = ""
        for member in memberList:
            memberName = userName(member)[1] + " " + userName(member)[2]
            members = memberName + ", " + members
        members = members.rstrip(", ")
        print 'The project can not be wiped out at this time.\nThere are still members in this project.\nPlease ask "%s" to unjoin project first.' % (
            members
        )
        sys.exit()

    # shared project delete
    if 3 > 2:
        if os.path.islink(projPathAtLocal):
            os.remove(projPathAtLocal)

        if os.path.exists(homePath + "/.mailboxlist"):
            UnjoinMailSub(ProjToBeUnjoind, pid, secIdN, ".mailboxlist")
        if os.path.exists(homePath + "/.subscriptions"):
            UnjoinMailSub(ProjToBeUnjoind, pid, secIdN, ".subscriptions")

        if secId == "BIOINFO":
            projRoot0 = "//genomics"
        elif secId == "BIOSTAT":
            projRoot0 = "/proj/BIOSTAT"
        if pid == 3:
            pathToXML = projPathAtRemote + "/.common/" + ".proj_info.xml"
        elif pid in [1, 2]:
            pathToXML = projPathAtRemote + "/.proj_info.xml"
        if os.path.exists(pathToXML):
            xmldoc = minidom.parse(pathToXML)
            cNodes = xmldoc.childNodes
            projNum = cNodes[0].getElementsByTagName("projNum")
            projNameP = projPathInfo[3]
            projInfoFileName = os.path.basename((projNum)[0].firstChild.nodeValue.strip())
            relativePathtoXML = projPathInfo[3]
            XMLLink = os.path.join(
                projRoot0, "Projects/.projInfo", (os.path.join(projNameP, projInfoFileName)).replace("/", "=>")
            )
            try:
                tempstring = 'rm "%s"' % (XMLLink)
                os.remove(XMLLink)
            except:
                aa = 0
        if pid == 3:
            PublicFolder = projRoot0 + "/Public/.projects/" + ProjToBeUnjoind
            if os.path.exists(PublicFolder):
                removePublic = 'rm -R -f "%s"' % (PublicFolder)
                os.system(removePublic)

        localMail = projPathAtLocal.replace(os.environ["HOME"], os.environ["HOME"] + "/mail")
        if os.path.exists(localMail):
            removeMail = 'rm -R -f "%s"' % (localMail)
            os.system(removeMail)

        projPathAtRemoteAP = projPathInfo[4]
        projNameA = projPathInfo[2]
        moveMain = 'rm -R -f "%s"' % (projPathAtRemote)
        os.system(moveMain)
        projPathAtLocal = projPathInfo[9]
        localPathPrefix = projPathInfo[8]
        localMail = projPathAtLocal.replace(os.environ["HOME"], os.path.join(os.environ["HOME"], "mail"), 1)
        if pidType == "private":
            snipTree(folderPathRaw=os.path.dirname(projPathAtLocal), stopRaw=localPathPrefix)  # local main
            snipTree(folderPathRaw=os.path.dirname(localMail), stopRaw=os.path.join(os.environ["HOME"], "mail"))
            snipTree(folderPathRaw=projPathAtRemoteAP, stopRaw=pathPrefix)
        else:
            snipTree(folderPathRaw=os.path.dirname(projPathAtLocal), stopRaw=localPathPrefix)  # local main
            snipTree(folderPathRaw=os.path.dirname(localMail), stopRaw=os.path.join(os.environ["HOME"], "mail"))
            snipTree(folderPathRaw=projPathAtRemoteAP, stopRaw=pathPrefix)
            remotePublicRoot = pathPrefix.replace("/Projects/shared", "/Public/.projects", 1)
            remotePublic = projPathAtRemoteAP.replace(pathPrefix, remotePublicRoot, 1)
            snipTree(folderPathRaw=remotePublic, stopRaw=remotePublicRoot)

        print "Wipeout operation is completed. Good-bye.\n"
def delProj(projPathAtRemote):
    import os,sys,pwd,stat
    from xml.dom import minidom
    from osWalk import walktree
    from userName import userName
    from UnjoinMail import UnjoinMailSub
    from pathInfo import pathInfo_d,pathInfo_ks
    from unjoinProj import unjoinProj
    from snipTree import snipTree
    
    ##################################
    projPathInfo=pathInfo_d(projPathAtRemote)
    # pathInfo: pathOutput=(pathAbs,projName,projNameA,projNameP,projNameAP,pathPrefix,secId,pidType)
    #                          0       1         2        3         4           5         6    7
    #                                                                                    -2   -1
    secId=projPathInfo[6]
    pidType=projPathInfo[7]
    projName=projPathInfo[1]
    projNameP=projPathInfo[3]
    pathPrefix=projPathInfo[5]
    if pidType=='private':
        pid=1
    elif pidType=='shared':
        pid=3
    else: sys.exit("Wrong project type, contact support")  
    if secId=='BIOSTAT':
        secIdN=1
    elif secId=='BIOINFO':
        secIdN=2
    else: sys.exit("Wrong section ID, contact support")    
    
    if projPathInfo[7]=='shared':
        print "\nYou are going to delete a project with the following parameters:"
        print "            Section : %s" %(projPathInfo[6])
        print "       Project Type : %s" %(projPathInfo[7])
        print " Local Project Path : %s" %(projPathInfo[9])
        print "Remote Project Path : %s\n" %(projPathInfo[0])  
        pathVerify=raw_input("Is the above information correct [y] (y/n) ? " )
        pathVerify=pathVerify.upper()
        #print pathVerify
        while not (pathVerify in ["","Y","N","YES","NO"]):
            print "Please answer with \"y\" or \"n\" "
            pathVerify=raw_input("Are these correct [y] (y/n)? " ) 
            pathVerify=pathVerify.upper()
        if pathVerify in ["N","NO"]:
            sys.exit("Please change to your home directory and rerun the start.project.")    
    
    ###########################################
    projPathAtRemote=projPathInfo[0]           
    ProjToBeUnjoind=projPathInfo[1]            

    ###########################################

    while not os.path.exists(projPathAtRemote):      
        print "\nThere is no project as your input (\'%s\'). \nPlease verify the project name and directory path.\n" %(projPathAtRemote)    
        continueDel=raw_input("Do you wan to specify another project to delete? y/n: ")
        print "\n"
        if (continueDel.strip().upper() == 'N'): 
            sys.exit("Good-bye.\n")
            break
        elif (continueDel.strip().upper() != 'Y'):
            print "Please answer with y or n"
        else:    
            projPathAtRemote = raw_input("Please input the name of the project which you want to delete: ")    

    ############################################
    
    # get local proj path ###
    if pid in [1,2]:   
        projPathAtLocal=os.environ['HOME']+'/MyProjects_'+secId+'/private'+'/'+ProjToBeUnjoind    
    else:
        projPathAtLocal=os.environ['HOME']+'/MyProjects_'+secId+'/shared'+'/'+ProjToBeUnjoind
    
    homePath=os.environ['HOME']
    os.chdir(os.environ['HOME'])
    
    #  Initialize as in the start.project #######
    startprojectXML = r'//genomics/lib/start.project/start.project.xml'
    BIOINFOprojRootPath = r'//genomics/Projects'
    BIOSTATprojRootPath = r'/proj/BIOSTAT/Projects'
    USERprojRootPathPre = r'MyProjects'
    SHAREDPATH = r'shared'
    PRIVATEPATH = r'private'
    
    ###############
    if pidType == 'private':
        try:    
            unjoinProj(projPathAtRemote=projPathAtRemote,pattern='non-verbose',pd='Tt')
        except:
            sys.exit("Errors. Pleasee contact support.")
        print "Deleting.... Please wait.\n   .... "    
        sys.exit("Delete completed. Good bye.")
    ################
    
    
    ################
    continueAsk=0
    while continueAsk==0:
        projExist="No"
        if ( not(ProjToBeUnjoind=='')) :  
            cask=0
            while cask==0:
                string1='Are you sure to delete the whole project \'%s\'  y/n ?: ' %(ProjToBeUnjoind) 
                AreYouSure=raw_input(string1)
                if (AreYouSure.strip().upper() == 'Y'): 
                    print "\nDeleting. Please wait... \n ......\n"
                    continueAsk=1
                    break
                elif (AreYouSure.strip().upper() == 'N'):
                    continueAsk=1
                    print '\n Good-bye.\n'
                    sys.exit()
                else:
                    print "Please answer with y or n"
        else:
            print "\nThere is no project as your input. \nPlease verify the directory path and the project name to be deleted.\n"  #(\'%s\')%(ProjToBeUnjoindRawInput)
            while True:        
                continueDel=raw_input("Do you wan to specify another project to delete? y/n: ")
                print "\n"
                if (continueDel.strip().upper() == 'Y'):           
                    break
                elif (continueDel.strip().upper() == 'N'):
                    print "Good-bye"
                    continueAsk=1
                    sys.exit()
                    break
                else:
                    print "Please answer with y or n"
    #############################################
    DirFileInfo=[] 
    memberList=[] 
    if os.path.exists(projPathAtRemote):
       for (basepath, children) in walktree(projPathAtRemote,False):
          for child in children:
             DirFile=os.path.join(basepath, child)
             folderOwner=pwd.getpwuid(os.stat(DirFile)[4])[0]        #lstat ==>stat
             if os.environ["USER"]!=folderOwner:
                GidOfjoinProjFolder=os.stat(projPathAtRemote)[5]     
                if (GidOfjoinProjFolder in os.getgroups()):
                    if (not (oct(os.stat(DirFile)[stat.ST_MODE] & 0777)[2] in ['7','6','3','2'])) and (not (oct(os.stat(DirFile)[stat.ST_MODE] & 0777)[3] in ['7','6','3','2'])): 
                        if not(folderOwner in memberList):
                            #print DirFile
                            DirFileInfo.append(DirFile)
                            memberList.append(folderOwner)
                else:
                    print "%s, which is belong to %s, is not allowed to be deleted." %(DirFile, userName(folderOwner)[1]+userName(folderOwner)[2])
                    sys.exit()
             elif (oct(os.lstat(DirFile)[stat.ST_MODE] & 0777)[1:3]!=['7','7','7']): 
                unlock='chmod ugo=rwx \"%s\"' %(DirFile)
                os.system(unlock)
       if os.environ["USER"]==pwd.getpwuid(os.stat(projPathAtRemote)[4])[0]:
          if (oct(os.lstat(projPathAtRemote)[stat.ST_MODE] & 0777)[1:3]!=['7','7','7']):
                unlock='chmod ugo=rwx \"%s\"' %(projPathAtRemote)
                os.system(unlock)
        
    if len(memberList)>=1:
       members=''
       for member in memberList:
          memberName=userName(member)[1]+' '+userName(member)[2]
          members=memberName+', '+members
       members=members.rstrip(', ')
       print "The project can not be deleted at this time.\nThere are still members in this project.\nPlease ask \"%s\" to unjoin project first." %(members)
       sys.exit()
    
     # shared project delete
    
    if 3>2:
        if os.path.islink(projPathAtLocal):
            os.remove(projPathAtLocal)
        
        if os.path.exists(homePath+'/.mailboxlist'):
           UnjoinMailSub(ProjToBeUnjoind,pid,secIdN,'.mailboxlist')
        if os.path.exists(homePath+'/.subscriptions'):
           UnjoinMailSub(ProjToBeUnjoind,pid,secIdN,'.subscriptions')
        
        if secId=='BIOINFO':
           projRoot0='//genomics'
        elif secId=='BIOSTAT':
           projRoot0='/proj/BIOSTAT'
        pathToXML=projPathAtRemote+'/.common/'+'.proj_info.xml'
        if os.path.exists(pathToXML):
            xmldoc=minidom.parse(pathToXML)  
            cNodes=xmldoc.childNodes
            projNum=cNodes[0].getElementsByTagName("projNum")
            projNameP=projPathInfo[3]            
            projInfoFileName=os.path.basename((projNum)[0].firstChild.nodeValue.strip())
            relativePathtoXML=projPathInfo[3]
            XMLLink=os.path.join(projRoot0,'Projects/.projInfo',projInfoFileName.replace('/','=>'))
            try:            
                os.remove(XMLLink)
                os.remove('.'+XMLLink)
            except:
                aa=0 
        PublicFolder=projRoot0+'/Public/.projects/'+ProjToBeUnjoind
        if os.path.exists(PublicFolder):
            removePublic='rm -R -f \"%s\"' %(PublicFolder)
            os.system(removePublic)
        
        localMail=projPathAtLocal.replace(os.environ['HOME'],os.environ['HOME']+'/mail')
        if os.path.exists(localMail):
            removeMail='rm -R -f \"%s\"' %(localMail)
            os.system(removeMail)
        
        projPathAtRemoteAP=projPathInfo[4]  
        projNameA=projPathInfo[2]           
        if projPathAtRemote!=os.path.join(projPathAtRemoteAP,'.'+projInfoFileName):
            moveMain='mv \"%s\" \"%s\"' %(projPathAtRemote, os.path.join(projPathAtRemoteAP,'.'+projInfoFileName))
            os.system(moveMain)
            newDeletedName=(os.path.join(projNameP,projInfoFileName)).replace('/','=>')
            move2deleted=os.path.join(os.path.dirname(pathPrefix),'.deleted',newDeletedName)
            move2='mv \"%s\" \"%s\"' %(os.path.join(projPathAtRemoteAP,'.'+projInfoFileName),move2deleted)
            os.system(move2)
            projInfoLink=os.path.join(os.path.dirname(pathPrefix),'.projInfo',newDeletedName)
            if os.path.exists(projInfoLink):
                os.remove(projInfoLink)
        projPathAtLocal= projPathInfo[9]
        localPathPrefix=projPathInfo[8]
        localMail=projPathAtLocal.replace(os.environ['HOME'],os.path.join(os.environ['HOME'],'mail'),1)
        if pidType=='shared':
           snipTree(folderPathRaw=os.path.dirname(projPathAtLocal), stopRaw=localPathPrefix)  #local main
           snipTree(folderPathRaw=os.path.dirname(localMail), stopRaw=os.path.join(os.environ['HOME'],'mail')) 
           snipTree(folderPathRaw=projPathAtRemoteAP, stopRaw=pathPrefix)
           remotePublicRoot=pathPrefix.replace('/Projects/shared', '/Public/.projects',1)
           remotePublic=projPathAtRemoteAP.replace(pathPrefix,remotePublicRoot,1)
           snipTree(folderPathRaw=remotePublic, stopRaw=remotePublicRoot)
           
        print "Delete completed. Good-bye."
def unjoinProj(projPathAtRemote,pattern,pd='Ff'):
    import os, sys, getpass
    import time, pwd
    import subprocess as sp
    from xml.dom.ext.reader import Sax2
    from xml.xpath import Evaluate
    import shutil
    import project
    from UnjoinMail import UnjoinMail
    from xml.dom import minidom
    from pathInfo import pathInfo_base, pathInfo_ks
    from snipTree import snipTree
    # cd home
    homePath=os.environ['HOME']
    os.chdir(os.environ['HOME'])
    # Initialize as in start.project
    startprojectXML = r'//genomics/lib/start.project/start.project.xml'
    BIOINFOprojRootPath = r'//genomics/Projects'
    BIOSTATprojRootPath = r'/proj/BIOSTAT/Projects'
    USERprojRootPathPre = r'MyProjects'
    SHAREDPATH = r'shared'
    PRIVATEPATH = r'private'                 
    # --------------- 
    projPathInfo=pathInfo_base(projPathAtRemote)
    pathInfo_ks(projPathInfo,type='unjoin')
    # pathInfo: pathOutput=(pathAbs,projName,projNameA,projNameP,projNameAP,pathPrefix,secId,pidType,localPathPrefix,projPathAtLocal)
    #                          0       1         2        3         4           5         6    7            8             9
    #                                                                                                       -2            -1
    if pd=='Ff':
        print "\nYou are going to unjoin a project with the following parameters:"
    else:
        print "\nYou are going to delete a project with the following parameters:"
    print "                Section : %s" %(projPathInfo[6])
    print "           Project Type : %s" %(projPathInfo[7])
    print "Local Project Path : %s\n" %(projPathInfo[9])
    pathVerify=raw_input("Are you sure [y] (y/n)? " )
    pathVerify=pathVerify.upper()
    while not (pathVerify in ["","Y","N","YES","NO"]):
        print "Please answer with \"y\" or \"n\" "
        pathVerify=raw_input("Are you sure to take action on this project [y] (y/n) ? " ) 
        pathVerify=pathVerify.upper()
    if pathVerify in ["N","NO"]:
        sys.exit("Start project program exited.")    
    
    secId=projPathInfo[6]
    pidType=projPathInfo[7]
    projName=projPathInfo[1]   
    # give proj path (with proj name), relative to pathPrefix as in pathInfo.py
    projNameP=projPathInfo[3] 
    projPathAtRemote= projPathInfo[0]   #abs proj path at remote
    projPathAtRemoteAP=projPathInfo[4]
    pathPrefix=projPathInfo[5]
    
    if pidType=='private':
        pid=1
    elif pidType=='shared':
        pid=3
    else: sys.exit("Wrong project type, contact support")  
    if secId=='BIOSTAT':
        secIdN=1
    elif secId=='BIOINFO':
        secIdN=3
    else: sys.exit("Wrong section ID, contact support")           
    while not os.path.exists(projPathAtRemote):      
        print "\nThere is no project as your input (\'%s\'). \nPlease verify the directory path and the project name.\n" %(projPathAtRemote)    
        continueDel=raw_input("Do you wan to specify another project to Unjoin? y/n: ")
        print "\n"
        if (continueDel.strip().upper() == 'N'): 
            sys.exit("Good-bye.\n")
            break
        elif (continueDel.strip().upper() != 'Y'):
            print "Please answer with y or n"
        else:    
            projPathAtRemote = raw_input("Please input the name of the project which you want to Unjoin: ")  
    #############################################################################
    # Get local proj path ###
    # ProjToBeUnjoind=projPathAtRemote.split('/')[-1]    
    # name of the project to be unjoined
    ProjToBeUnjoind=projPathInfo[1] 
    if pid in [1,2]:   
        projPathAtLocal=os.environ['HOME']+'/MyProjects_'+secId+'/private'+'/'+ProjToBeUnjoind    
    else:
        projPathAtLocal=os.environ['HOME']+'/MyProjects_'+secId+'/shared'+'/'+ProjToBeUnjoind
    #############################################################################    
    # 1. Permission check
    # Check for ownerhip and postfix of ANALYST_XXX
            
    # 2. Rename the ANALYST_XXX to .ANALYST_XXX +timeTag or /proj/.../proj_name to /proj/.../.proj_name+timeTag
    # 3. Delete the symbolic link at /Users/XXuserXX/MyProjects_BIOINFO/shared/XXX  [genomics can be biostatistics] 
    #############################################################################
            
    if pid!=3:        
        UnjoinProjSubFolderPath=projPathAtRemote     
        projPathAtRemoteNoname=projPathInfo[4]          
        if (not os.path.exists(UnjoinProjSubFolderPath)):                      
            if pd=='Ff':
                sys.exit(""" Unjoin has been terminated by the remote system. The project can not be Unjoind. \n \
             \n Please contact the system administrator\n""")          # 0.1 : check whether path exists
            else:
                sys.exit(""" Delete has been terminated by the remote system. \n \
             \n Please contact the system administrator\n""") 
        else:
            OwnerOfUnjoinProjSubFolder=pwd.getpwuid(os.stat(UnjoinProjSubFolderPath)[4])[0]      
            if (os.environ["USER"]!=OwnerOfUnjoinProjSubFolder):
                if pd=='Ff':
                    print 'Unjoin can not be executed, since the folder %s is not owned by you( %s ). \n Please ask %s or contact system administrator to carry out this unjoin action' \
                      %(UnjoinProjSubFolderPath, os.environ["USER"], OwnerOfUnjoinProjSubFolder)   # 0.2 : check file owners 
                else:
                    print 'Delete can not be executed, since the folder %s is not owned by you( %s ). \n Please ask %s or contact system administrator to carry out this action' \
                      %(UnjoinProjSubFolderPath, os.environ["USER"], OwnerOfUnjoinProjSubFolder)   # 0.2 : check file owners 
            else:
                if secId=='BIOSTAT':
                    projRoot0=BIOSTATprojRootPath
                else:
                    projRoot0=BIOINFOprojRootPath
                pathToXML=projPathAtRemote+'/.proj_info.xml'
                xmldoc=minidom.parse(pathToXML)  # '/genomics/lib/start.project/test.xml'
                cNodes=xmldoc.childNodes
                projNum=cNodes[0].getElementsByTagName("projNum")
                projInfoFileName=(projNum)[0].firstChild.nodeValue.strip() 
                newFolderPath=projPathInfo[4]  
                projInfoFileNameNoPath=os.path.basename(projInfoFileName)
                newNameForTheUnjoinProjectSubFolder=os.path.join(newFolderPath,'.'+projInfoFileNameNoPath)
                try:
                    commonPublic(dirFs=UnjoinProjSubFolderPath) 
                    shutil.move(UnjoinProjSubFolderPath, newNameForTheUnjoinProjectSubFolder)
                    removeLocalSymbolicLink="rm -R -f \"%s\"" %(projPathAtLocal)
                    os.system(removeLocalSymbolicLink)
                    relink='rm \"%s/.projInfo/%s\"' %(projRoot0,projInfoFileName.replace('/','=>'))
                    os.system(relink) 
                except:
                    sys.exit(""" Unjoin has been terminated by the remote system. The project can not be Unjoind. \n \
                             \n Please contact the system administrator\n""")   
    elif pid==3:
        UnjoinProjSubFolderPath=projPathAtRemote+'/'+'ANALYST_'+os.environ["USER"]        

        if (not os.path.exists(UnjoinProjSubFolderPath)):                      
            if pd=='Ff':            
                print '''Unjoin can not be executed, since the folder %s does not exist. You are currently not a member of the project %s \n''' \
                   %(str('ANALYST_'+os.environ["USER"]), projPathAtRemote)     # why not LOGNAME?
            else:
                print '''Delete can not be executed, since the folder %s does not exist. You are currently not a member of the project %s \n''' \
                   %(str('ANALYST_'+os.environ["USER"]), projPathAtRemote)     # why not LOGNAME?                
            sys.exit()
        else:
            OwnerOfUnjoinProjSubFolder=pwd.getpwuid(os.stat(UnjoinProjSubFolderPath)[4])[0]      
            if (os.environ["USER"]!=OwnerOfUnjoinProjSubFolder):  
                print 'Unjoin can not be executed, since the folder %s is not owned by you( %s ). \n Please ask %s or contact system administrator to carry out this unjoin action' \
                      %(UnjoinProjSubFolderPath, os.environ["USER"], OwnerOfUnjoinProjSubFolder)              
            else:
                timeTag=time.strftime("_%Y%b%d%H%M%SSN")+str(int(1000*time.time()))   #1/1000 second accurate
                newNameForTheUnjoinProjectSubFolder=projPathAtRemote+'/.'+'ANALYST_'+os.environ["USER"]+timeTag
                try:
                    commonPublic(dirFs=UnjoinProjSubFolderPath)   
                    UnjoinProjSubFolderPath="mv \"%s\" \"%s\"" %(UnjoinProjSubFolderPath, newNameForTheUnjoinProjectSubFolder)
                    os.system(UnjoinProjSubFolderPath)
                    string1='chmod -R uog=rwx \"%s\"' %(newNameForTheUnjoinProjectSubFolder)   
                    os.system(string1) 
                    removeLocalSymbolicLink="rm -R -f \"%s\"" %(projPathAtLocal)
                    os.system(removeLocalSymbolicLink)
                except:
                    sys.exit(""" Unjoin has been terminated by the remote system. The project can not be Unjoind. \n \
                             \n Please contact the system administrator\n""")   
    # ###########################################################################
    
    # Mail unsubscription
    # Need to readin .maillist from user's home directory
    # readout project type id and section ID from the symbolic link's abs path, i.e., projPathAtRemote
    
    # 1. remove items in /Users/XXX/.mailboxlist, .mailboxlist.bak is untouched.
    try:
        UnjoinMail(projname=ProjToBeUnjoind,pid=pid,secIdN=secIdN)        
    except:
        aa=0
    # ###########################################################################
    string3=os.environ['HOME']+'/mail'+'/MyProjects_'+secId+'/'+pidType+'/'+ProjToBeUnjoind
    if  os.path.islink(string3): 
        if (os.environ["USER"]!=pwd.getpwuid(os.lstat(string3)[4])[0]):
            print 'Warning: %s does not belong to you. Please ask %s to delete it' %(string3,pwd.getpwuid(os.stat(string3)[4])[0])
        else:
            string4='rm -R -f '+string3
            try:
                os.system(string4)
            except:
                aa=0
    elif not os.path.exists(string3):   
        print "Note: %s does not exists" %(string3)
    elif (os.environ["USER"]!=pwd.getpwuid(os.stat(string3)[4])[0]):  
        print 'Warning: %s does not belong to you. Please ask %s to delete it' %(string3,pwd.getpwuid(os.stat(string3)[4])[0])
    else:
        string4='rm -R -f '+string3
        try:
            os.system(string4)     
        except:
            aa=0   
    # look through files in .common and Public/.projects    
    commonFiles=os.path.join(projPathAtRemote,'.common')
    commonPublic(dirFs=commonFiles)
    if secId=='BIOINFO':
       publicFiles=os.path.join('/proj','genomics','Public','.projects',ProjToBeUnjoind)
    elif secId=='BIOSTAT':
       publicFiles=os.path.join('/proj','BIOSTAT','Public','.projects',ProjToBeUnjoind)
    commonPublic(dirFs=publicFiles)
    # write unjoin date into .proj_info.xml
    projType=pid
    if projType==3:    
        pathToXML=projPathAtRemote+'/.common/'+'.proj_info.xml'
        projInfoXMLbkup=projPathAtRemote+'/.common/'+'.proj_info_bkup.xml'
    elif projType in [1,2]:
        pathToXML=newNameForTheUnjoinProjectSubFolder+'/.proj_info.xml'
        projInfoXMLbkup=newNameForTheUnjoinProjectSubFolder+'/.proj_info_bkup.xml' 
    
    try:
        tempstring='cp -f \"%s\" \"%s\"' %(pathToXML, projInfoXMLbkup)
        os.system(tempstring)
    except: 
        print 'Warning: Can not handle the XML for proj info' 
    try:
        xmldoc=minidom.parse(pathToXML) 
        cNodes=xmldoc.childNodes
        projNum=cNodes[0].getElementsByTagName("projNum")
        projInfoFileName=(projNum)[0].firstChild.nodeValue.strip()
        analystList=cNodes[0].getElementsByTagName("analyst")
        for item in analystList:
            if item.getElementsByTagName("loginName")[0].firstChild.nodeValue.strip()==os.environ['USER']:
                item.getElementsByTagName("unjoinDate")[0].firstChild.nodeValue=time.ctime()
                file = open(pathToXML, 'w')  
                file.write(xmldoc.toxml())
                file.close()
                break
            
        tempstring='rm \"%s\"' %(projInfoXMLbkup)
        os.system(tempstring)
    except:
        print 'Warning: Can not handle the XML for proj info'
    if projType==1:
        move2deleted=os.path.join(os.path.dirname(os.path.dirname(pathPrefix)),'.deleted',projInfoFileName.replace('/','=>'))
        move2='mv \"%s\" \"%s\"' %(newNameForTheUnjoinProjectSubFolder,move2deleted)
        os.system(move2)  
    projPathAtLocal= projPathInfo[9]
    localPathPrefix=projPathInfo[8]
    localMail=projPathAtLocal.replace(os.environ['HOME'],os.path.join(os.environ['HOME'],'mail'),1)
    if pidType== 'private':
       snipTree(folderPathRaw=os.path.dirname(projPathAtLocal), stopRaw=localPathPrefix)  #local main     
       snipTree(folderPathRaw=os.path.dirname(localMail), stopRaw=os.path.join(os.environ['HOME'],'mail'))  
       snipTree(folderPathRaw=projPathAtRemoteAP, stopRaw=pathPrefix)
    else:
       snipTree(folderPathRaw=os.path.dirname(projPathAtLocal), stopRaw=localPathPrefix)  #local main
       snipTree(folderPathRaw=os.path.dirname(localMail), stopRaw=os.path.join(os.environ['HOME'],'mail')) 
    ############################## Good bye ###################################
    if pd=='Ff':
        print "Unjoin completed. Good bye.\n "
        if iscurrenmember!=-1 and pidType_old=='shared':
            remotePublic=os.path.join(pathAbs_new,'ANALYST_'+os.environ['USER'],'PUBLIC')
            try:
                if os.path.lexists(remotePublic) or os.path.isfile(remotePublic):   
                    if not (oct(os.lstat(remotePublic)[stat.ST_MODE] & 0777)[1]=='7'):
                        unlock='chmod ug+rwx \"%s\"' %(remotePublic)
                        os.system(unlock)
                    os.remove(remotePublic)
                os.symlink(os.path.join(pathAbs_new,'.public'),remotePublic)
            except:
                if sponsorUnjoined!='yes' or pidType_old!='shared':
                    print "project moved. However, your remote Public folder can not be handled. Please contact support."
localPathPrefix_old=projPathInfo_old[8]
localMail=projPathAtLocal_old.replace(os.environ['HOME'],os.path.join(os.environ['HOME'],'mail'),1)
if pidType_old== 'private':
   snipTree(folderPathRaw=os.path.dirname(projPathAtLocal_old), stopRaw=localPathPrefix_old)  #local main     
   snipTree(folderPathRaw=os.path.dirname(localMail), stopRaw=os.path.join(os.environ['HOME'],'mail'))  
   snipTree(folderPathRaw=projPathAtRemoteAP_old, stopRaw=pathPrefix_old)
else:
   snipTree(folderPathRaw=os.path.dirname(projPathAtLocal_old), stopRaw=localPathPrefix_old)  #local main
   snipTree(folderPathRaw=os.path.dirname(localMail), stopRaw=os.path.join(os.environ['HOME'],'mail'))
   if os.environ['USER']==sponsorId:
       snipTree(folderPathRaw=projPathAtRemoteAP_old, stopRaw=pathPrefix_old)
       remotePublicRoot=pathPrefix_old.replace('/Projects/shared', '/Public/.projects',1)
       remotePublic=projPathAtRemoteAP_old.replace(pathPrefix_old,remotePublicRoot,1)
       snipTree(folderPathRaw=remotePublic, stopRaw=remotePublicRoot)
    
# email members: project moved, please update. 
if iscurrenmember==0:
    try:
        s=SMTPVerify()