import arcpy 
import os, string

''' Update the following five variables before running the script.'''
#Set major Release Version (10.6, 10.7, 10.8)
version = "10.8"
#Set path to SDE connection file using Geodatabase Admin
myWorkspace = r"C:\Temp\Geodatabase.sde" 
#Adapt path if not installed in default location
gp_history_xslt = r"C:\Program Files (x86)\ArcGIS\Desktop{0}\Metadata\Stylesheets\gpTools\remove geoprocessing history.xslt".format(version) 
#Set output dir for XML files (if not empty, content will be removed)
output_dir = r"D:\Temp\XML"
#Set this to either "SQL" (for MS SQL Server), "Postgres" or "Oracle" if your db has spatial views. If not you may set it to "".
db_type = "SQL" 

def RemoveHistory(myWorkspace, gp_history_xslt, output_dir):
    ##Removes GP History for the workspace.
    arcpy.XSLTransform_conversion(
            source=myWorkspace, 
            xslt=gp_history_xslt, 
            output="{0}\sde_xslttransformation.xml".format(output_dir), 
            xsltparam="")
    print "Completed xml coversion on {0}".format(myWorkspace)
    arcpy.MetadataImporter_conversion(
            source="{0}\sde_xslttransformation.xml".format(output_dir), 
            target=myWorkspace)
    print "Imported XML on {0}".format(myWorkspace)
    
    ##Removes GP History for feature dataset stored feature classes, and feature classes in the File Geodatabase.
    arcpy.env.workspace = myWorkspace
    
    for fds in arcpy.ListDatasets('','feature') + ['']:
        for fc in arcpy.ListFeatureClasses('','',fds):
            data_path = os.path.join(myWorkspace, fds, fc)
            if isNotSpatialView(myWorkspace, fc):
                removeAll(data_path, fc, gp_history_xslt, output_dir)

def isNotSpatialView(myWorkspace, fc):
    ##Determines if the item is a spatial view and if so returns True to listFcsInGDB()    
    if db_type <> "":
        desc = arcpy.Describe(fc)
        fcName = desc.name
        #Connect to the GDB
        egdb_conn = arcpy.ArcSDESQLExecute(myWorkspace)
        #Execute SQL against the view table for the specified RDBMS
        if db_type == "SQL":
            db, schema, tableName = fcName.split(".")
            sql = r"IF EXISTS(select * FROM sys.views where name = '{0}') SELECT 1 ELSE SELECT 0".format(tableName)
        elif db_type == "Oracle":
            schema, tableName = fcName.split(".")
            sql = r"SELECT count(*) from dual where exists (select * from user_views where view_name = '{0}')".format(tableName)
        elif db_type == "Postgres":
            db, schema, tableName = fcName.split(".")
            sql = r"SELECT EXISTS (SELECT FROM pg_views WHERE viewname  = '{0}')::int;".format(tableName)
        else: return True
        egdb_return = egdb_conn.execute(sql)
        if egdb_return == 0:
            return True
        else:
            return False
    else: return True

def removeAll(data_path, feature, gp_history_xslt, output_dir):
    ##Remove all GP History metadata from a feature class.
    arcpy.ClearWorkspaceCache_management()
    name_xml = os.path.join(output_dir, str(feature)) + ".xml"

    arcpy.XSLTransform_conversion(data_path, gp_history_xslt, name_xml)
    print "Completed xml coversion on {0}".format(feature)

    arcpy.MetadataImporter_conversion(name_xml, data_path)
    print "Imported XML on {0}".format(feature)

def makeDirectory(output_dir):
    ##Creates directory to store the xml tables of converted metadata. 
    if not arcpy.Exists(output_dir):
        os.mkdir(output_dir)
    ## If the directory is not empty, the content will be deleted.
    for filename in os.listdir(output_dir):
        file_path = os.path.join(output_dir, filename)
        try:
            if os.path.isfile(file_path) or os.path.islink(file_path):
                os.unlink(file_path)
            elif os.path.isdir(file_path):
                shutil.rmtree(file_path)
        except Exception as e:
            print('Failed to delete %s. Reason: %s' % (file_path, e))
            
if __name__ == "__main__":
    print "Workspace: {0}".format(myWorkspace)
    print "XSLT: {0}".format(gp_history_xslt)
    print "Output directory: {0}".format(output_dir)
    print "Database Type: {0}".format(db_type)
    makeDirectory(output_dir)
    RemoveHistory(myWorkspace, gp_history_xslt, output_dir)
print "Done Done"
