#!/usr/bin/python3
#
# Copyright (C) 2002
#
# This file is part of the email2trac utils
#
#       Copyright 2002 SURFsara
#
#       Licensed under the Apache License, Version 2.0 (the "License");
#       you may not use this file except in compliance with the License.
#       You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#       Unless required by applicable law or agreed to in writing, software
#       distributed under the License is distributed on an "AS IS" BASIS,
#       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#       See the License for the specific language governing permissions and
#       limitations under the License.
#
# vi:
#   set ts=4

"""
Author: Bas van der Vlies
Date  : 29 September 2205
Desc. : Delete Spam tickets from database. Else we get an lot of 
        tickets

"""

import os
import sys
import getopt
import shutil
try:
    from configparser import ConfigParser, MissingSectionHeaderError
except ImportError:
    from ConfigParser import ConfigParser, MissingSectionHeaderError

def ReadConfig(file, name):
    """
    Parse the config file
    """

    if not os.path.isfile(file):
        print('File %s does not exists' %file)
        sys.exit(1)

    config = ConfigParser()
    try:
        config.read(file)
    except MissingSectionHeaderError as detail:
        print(detail)
        sys.exit(1)

    # Use given project name else use defaults
    #
    if name:
        if not config.has_section(name):
            print("Not an valid project name: %s" %name)
            print("Valid names: %s" %config.sections())
            sys.exit(1)

        project = dict()
        for option in config.options(name):
            project[option] = config.get(name, option) 

    else:
        project = config.defaults()

    return project



def new_delete_spam(parameters):
    """
    This only works for trac versions higher or equal then 0.10
    """

    debug = int(parameters['debug'])
    DRY_RUN = parameters['DRY_RUN']
    VERBOSE = parameters['VERBOSE']

    project = parameters['project']


    env = Environment(project, create=0)
    db = env.get_db_cnx()

    cursor = db.cursor()
    cursor.execute("SELECT id FROM ticket WHERE  component = 'Spam';") 
    while 1: 
        row = cursor.fetchone()
        if not row:
            break 

        spam_id = row[0]

        if debug or DRY_RUN or VERBOSE:
            print("Deleting ticket %s" %spam_id)

        try:
            tkt = Ticket(env, spam_id, db)
        except util.TracError as detail:
                print(detail)
                continue

        if DRY_RUN:
            print('DRY_RUN: tkt.delete()')
        else:
            tkt.delete()

if __name__ == "__main__":
    import argparse

    class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter):
        pass

    parser = argparse.ArgumentParser(
        description="Delete Spam tickets from database.",
        formatter_class=CustomFormatter
    )
    parser.add_argument('-p', '--project', default=None, required=True, metavar='<projectname>', help=";")
    parser.add_argument('-f', '--file', metavar='<configfile>', default='/etc/email2trac.conf', help=";")
    parser.add_argument('-E', '--virtualenv', metavar='<path>', default='', help=";")
    parser.add_argument('-n', '--dry-run', action='store_true', default=False, help=";")
    parser.add_argument('-v', '--verbose', action='store_true', default=False, help=";")

    args = parser.parse_args()
    configfile = args.file
    project_name = args.project
    DRY_RUN = args.dry_run
    VERBOSE = args.verbose
    virtualenv = args.virtualenv

    if virtualenv and os.path.exists(virtualenv):
        activate_this = os.path.join(virtualenv, 'bin/activate_this.py')
        if os.path.exists(activate_this):
            exec(compile(open(activate_this, "rb").read(), activate_this, 'exec'), dict(__file__=activate_this))


    try:
        from trac import __version__ as trac_version
        from trac import config as trac_config
        from trac.env import Environment
        from trac.ticket import Ticket
        from trac import util

    except ImportError as detail:
        print("Can not find a a valid trac installation, solutions could be:")
        print("\tset PYTHONPATH")
        print("\tuse the --virtualenv <dir> option")
        sys.exit(1) 

    # Determine major trac version used to be in email2trac.conf
    # Quick hack for 0.12
    #
    l = trac_version.split('.')
    version = '.'.join(l[0:2])

    if VERBOSE:
        print("Found trac version: %s" %version)

    ## We only support versions 0.11 and 0.12
    #
    if not version in ['0.11', '0.12', '1.0', '1,1', '1.2']:
        print('Trac version %s is not supported' %(version))

    settings = ReadConfig(configfile, project_name)
    if 'project' not in settings:
        print('No project defined in config file, eg:\n\t project: /data/trac/bas')
        parser.print_help()
        sys.exit(1)

    settings['DRY_RUN'] = DRY_RUN
    settings['VERBOSE'] = VERBOSE

    new_delete_spam(settings)

    print('Spam is deleted successfully..')
# EOB
