#!/usr/bin/python3
# Copyright (C) 2020 Jelmer Vernooij <jelmer@debian.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

"""Functions for working with lintian data."""

from typing import Optional


def read_debhelper_lintian_data_file(f, sep):
    for lineno, line in enumerate(f, 1):
        if line.startswith("#"):
            continue
        if not line.strip():
            continue
        line = line.rstrip("\n")
        try:
            key, value = line.split(sep, 1)
        except ValueError:
            key = line
            value = None
        yield key, value


def read_obsolete_sites(f):
    for line in f:
        line = line.strip()
        if not line:
            continue
        if line.startswith('#'):
            continue
        yield line


OBSOLETE_SITES_PATH = '/usr/share/lintian/data/obsolete-sites/obsolete-sites'
_obsolete_sites = None


def is_obsolete_site(parsed_url) -> Optional[str]:
    global _obsolete_sites
    if _obsolete_sites is None:
        with open(OBSOLETE_SITES_PATH, 'r') as f:
            _obsolete_sites = list(read_obsolete_sites(f))
    for site in _obsolete_sites:
        if parsed_url.hostname.endswith(site):
            return site
    else:
        return None
