Main function

def main():
    """
    Main function
    """

    global _DEBUG_
    _DEBUG_ = False

    global tpb_url
    global tpb_categories
    global transmission_rcp
    global tvdbapi_tag

    # Init locals variables
    serie_title = None
    search_type = None
    serie_season = ""
    serie_episode = ""
    seeders_min = 0
    download_tag = False
    display_all_tag = False
    hd_tag = False
    save_torrent_dir = None

    # Manage args
    try:
        opts, args = getopt.getopt(sys.argv[1:], "T:S:t:s:e:l:qdc:p:aiVDhv")
    except getopt.GetoptError as err:
        # Print help information and exit:
        print("Syntax error, %s" % str(err))
        sys.exit(2)
    for opt, arg in opts:
        if opt in ("-t"):
            try:
                serie_title = arg
            except:
                printVersion()
                sys.exit(1)
        elif opt in ("-s"):
            try:
                serie_season = arg
            except:
                printVersion()
                sys.exit(1)
        elif opt in ("-e"):
            try:
                serie_episode = arg
            except:
                printVersion()
                sys.exit(1)
        elif opt in ("-l"):
            try:
                seeders_min = int(arg)
            except:
                printVersion()
                sys.exit(1)
        elif opt in ("-q"):
            hd_tag = True
        elif opt in ("-d"):
            download_tag = True
        elif opt in ("-c"):
            transmission_rcp = arg
        elif opt in ("-p"):
            try:
                tpb_url = arg
            except:
                printVersion()
                sys.exit(1)
        elif opt in ("-a"):
            display_all_tag = True
        elif opt in ("-i"):
            tvdbapi_tag = False
        elif opt in ("-h"):
            printVersion()
            printSyntax()
            sys.exit(0)
        elif opt in ("-v"):
            printVersion()
            sys.exit(0)
        elif opt in ("-V"):
            _DEBUG_ = True
            # Verbose mode is ON
            logging.basicConfig(
                level=logging.INFO,
                format='%(asctime)s %(levelname)s - %(message)s',
                datefmt='%d/%m/%Y %H:%M:%S',
            )
            logging.debug("Verbose mode is ON")
        elif opt in ("-D"):
            _DEBUG_ = True
            # Debug mode is ON
            logging.basicConfig(
                level=logging.DEBUG,
                format='%(asctime)s %(levelname)s - %(message)s',
                datefmt='%d/%m/%Y %H:%M:%S',
            )
            logging.debug("Debug mode is ON")
        elif opt in ("-T"):
            if arg=='pb' or arg=='t411':
                search_type=arg
            else:
                logging.error('Invalid type of search : t411 (torrent411) or pb (Piracy Bay). ')
                sys.exit(1)
        elif opt in ("-S"):
            logging.info('Saving torrent from torrent411 to: %s' % arg)
            save_torrent_dir = arg
        # Add others options here...
        else:
            printSyntax()
            sys.exit(1)
    
    if (not _DEBUG_):
        # Set default logging message to ERROR
        logging.basicConfig(
            level=logging.ERROR,
            format='%(asctime)s %(levelname)s - %(message)s',
            datefmt='%d/%m/%Y %H:%M:%S',
        )

    logging.info("Running %s version %s" % (__appname__, __version__))

    # Test args
    if (serie_title is None):
        # A serie's title is needed... always
        logging.error("Need a serie's title. Use the -t tag.")
        sys.exit(1)
    else:
        logging.info("Search for title %s" % serie_title)
    if search_type==None:
        logging.error("Need a type of search : t411 (torrent411) or pb (Piracy Bay). Use the -T tag.")
        sys.exit(1)
    else:
        if search_type=='pb':
            logging.info("Search on PiracyBay")
        else:
            logging.info("Search on torrent411")
    if (serie_season != ""):
        # Optionnal season number
        logging.info("Search for season %s" % serie_season)
    if (serie_episode != ""):
        # Optionnal episode number
        logging.info("Search for episode %s" % serie_episode)
    if (download_tag and not transmissionrpc_tag):
        logging.error("-d tag need the TransmissionRPC Python lib")
        sys.exit(1)
    if (hd_tag):
        # HD tag is True: search only in the HD category
        tpb_categories.update(tpb_categories_hd)
        logging.info("Filter HD series")
    else:
        # By default search on all categories (SD and HD)
        tpb_categories.update(tpb_categories_ld)
        tpb_categories.update(tpb_categories_hd)
    if (download_tag and display_all_tag):
        logging.error("-d tag can not be used with the -a tag")
        sys.exit(1)
    if (download_tag and not display_all_tag):
        logging.info("Download mode is ON")
        try:
            transmission_rcp_host, transmission_rcp_port = transmission_rcp.split(':')
            transmission_rcp_port = int(transmission_rcp_port)
        except:
            logging.error("Transmission RPC adress should be host:port")
            sys.exit(1)
        else:
            logging.info("Transmission RPC: host=%s / port=%s" % (transmission_rcp_host, transmission_rcp_port))
    else:
        logging.info("Download mode is OFF")
    if (display_all_tag):
        logging.info("Display all tag is ON")

    if (tvdbapi_tag):
        logging.info("TVDB API is installed")
    else:
        logging.info("TVDB API is not installed")
    if (save_torrent_dir and not download_tag):
        print("-S tag need to be used with -d tag")
        sys.exit(1)



    # According to user choice, search in PiracyBay or torrent411
    if search_type=='pb':    
        logging.info("Piracy Bay URL (use -p to overwrite): %s" % tpb_url)
        serie = series_pb(tpb_url = tpb_url, title=serie_title, season=serie_season, episode=serie_episode, seeders_min=seeders_min)
    else:
        serie = series_t411(title=serie_title, season=serie_season, episode=serie_episode, seeders_min=seeders_min, directory_download=save_torrent_dir)
    best = serie.getbest()

    # Display result
    if (best is not None):
        if (display_all_tag):
            logging.info("Display all results")
            for r in serie.getall():
                print("*"*79)
                print("Title:   %s" % r[0])
                print("Seeders: %s" % r[1])
                if search_type=='pb':
                    print("Magnet:  %s" % r[2])
                else:
                    print("Id:  %s" % r[2])
                # print("Torrent: %s" % r[3])
        else:
            logging.info("Best match is %s" % best[0])
            print("Title:   %s" % best[0])
            print("Seeders: %s" % best[1])
            if search_type=='pb':
                print("Magnet:  %s" % best[2])
            else:
               print("Id:  %s" % best[2])
            # print("Torrent: %s" % best[3])
    else:
        print("No torrent found for %s..." % serie_title)

    # Download
    if ((best is not None) and download_tag):
        uri = None
        if search_type=='pb':
            uri = best[2]
            logging.info("Send best magnet to Transmission")
            print("Uri:  %s" % uri)
        
        try:
            tc = transmissionrpc.Client(transmission_rcp_host, port=transmission_rcp_port)
        except:
            print("Error: Can not connect to Transmission (%s:%s)" % (transmission_rcp_host, transmission_rcp_port))
            print("Info: Transmission remote control access should be enabled on host %s, port %s" % (transmission_rcp_host, transmission_rcp_port))
            logging.info("Can not connect to Transmission (%s:%s)" % (transmission_rcp_host, transmission_rcp_port))
            sys.exit(1)
        else:
            logging.debug("Transmission connection completed")
        try:
            if search_type=='pb':
                tc.add_uri(best[2])
            else:
                tc.add(serie.downloadbest())
        except:
            logging.error("Error while sending download request to Transmission")
            sys.exit(1)
        else:
            print("Transmission start downloading...")

    # End of the game
    sys.exit(0)