# vim:set fileencoding=utf-8 et ts=4 sts=4 sw=4:
#
#   apt-listchanges - Show changelog entries between the installed versions
#                     of a set of packages and the versions contained in
#                     corresponding .deb files
#
#   Copyright (C) 2000-2006  Matt Zimmerman  <mdz@debian.org>
#   Copyright (C) 2006       Pierre Habouzit <madcoder@debian.org>
#   Copyright (C) 2016-2019  Robert Luberda  <robert@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 St, Fifth Floor, Boston, MA 02110-1301, USA.
#

import re
import os
import tempfile
import gzip
import errno
import fnmatch
import functools
import glob
import shutil
import shlex
import signal
import subprocess

import apt_pkg

from apt_listchanges import ALCLog
from apt_listchanges.ALChacks import _


def _numeric_urgency(u):
    urgency_map = {'critical'  : 1,
                   'emergency' : 1,
                   'high'      : 2,
                   'medium'    : 3,
                   'low'       : 4}

    return urgency_map.get(u.lower(), 99)


# pylint: disable=no-member
class ControlStanza:
    fields_to_read = ['Package', 'Source', 'Version', 'Architecture', 'Status']

    def __init__(self, s):
        field = None

        for line in s.split('\n'):
            if not line:
                break
            if line[0] in (' ', '\t'):
                if field:
                    setattr(self, field, getattr(self, field) + '\n' + line)
            else:
                field, value = line.split(':', 1)
                if field in self.fields_to_read:
                    setattr(self, field, value.lstrip())
                else:
                    field = None

    @property
    def source(self):
        return getattr(self, 'Source', self.Package).split(' ')[0]

    @property
    def installed(self):
        return hasattr(self, 'Status') and \
            self.Status.split(' ')[2] == 'installed'

    @property
    def version(self):
        return self.Version


class ControlParser:
    def __init__(self):
        self.stanzas = []
        self.index = {}

    def makeindex(self, field):
        self.index[field] = {}
        for stanza in self.stanzas:
            self.index[field][getattr(stanza, field)] = stanza

    def readfile(self, file):
        try:
            with open(file, encoding='utf-8', errors='replace') as f:
                self.stanzas += [
                    ControlStanza(x) for x in f.read().split('\n\n') if x]
        except Exception as ex:
            raise RuntimeError(_("Error processing '%(what)s': %(errmsg)s") %
                               {'what': file, 'errmsg': str(ex)}) from ex

    def readdeb(self, deb):
        try:
            command = ['dpkg-deb', '-f', deb] + ControlStanza.fields_to_read
            output = subprocess.check_output(command)
            self.stanzas.append(
                ControlStanza(output.decode('utf-8', 'replace')))
        except Exception as ex:
            raise RuntimeError(_("Error processing '%(what)s': %(errmsg)s") %
                               {'what': deb, 'errmsg': str(ex)}) from ex

    def find(self, field, value):
        if field in self.index:
            if value in self.index[field]:
                return self.index[field][value]
            return None
        for stanza in self.stanzas:
            if hasattr(stanza, field) and getattr(stanza, field) == value:
                return stanza
        return None


class ChangelogEntry:
    def __init__(self, header, path, package, source, version, urgency,
                 binnmu=False):
        self._header = header.strip()
        self._path = path
        self._package = package
        self._source = source
        self._version = version
        self._numeric_urgency = _numeric_urgency(urgency)
        self._trailer = ''
        self._content = ''
        self._binnmu = binnmu

    def set_trailer(self, trailer):
        self._trailer = trailer.rstrip()

    def add_content(self, content):
        if self._content:
            self._content += content
        elif not content.isspace():
            self._content = content

    @property
    def path(self):
        return self._path

    @property
    def package(self):
        return self._package

    @property
    def source(self):
        return self._source

    @property
    def version(self):
        return self._version

    @property
    def numeric_urgency(self):
        return self._numeric_urgency

    @property
    def binnmu(self):
        return self._binnmu

    @property
    def header(self):
        return self._header

    @property
    def trailer(self):
        return self._trailer

    @property
    def content(self):
        return self._content.rstrip()

    def __str__(self):
        result = self.header + '\n\n' + self.content + '\n\n' + self.trailer
        if self.header and self.trailer:
            return result
        return result.strip()
    __repr__ = __str__

    def __hash__(self):
        return hash((self._header, self.content, self._trailer, self._binnmu))

    def __eq__(self, other):
        if self.__class__ != other.__class__:
            return False
        return hash(self) == hash(other)


# Group changes by package. Within each package sort in reverse order by
# version number. Sort the groups by the highest urgency in each.
class EntrySorter:
    def __init__(self, entries):
        packages = set((entry.package for entry in entries))
        self.package_urgencies = {
            package: min((entry.numeric_urgency for entry in entries
                          if entry.package == package))
            for package in packages
        }
        # Since we want version numbers to be sorted in reverse but the other
        # keys to be sorted ascending, we need to create a mapping of version
        # numbers to descending indices.
        versions = sorted(set((entry.version for entry in entries)),
                          key=functools.cmp_to_key(apt_pkg.version_compare),
                          reverse=True)
        self.version_keys = {versions[i]: i for i in range(len(versions))}

    def key_func(self, entry):
        return (self.package_urgencies[entry.package], entry.package,
                self.version_keys[entry.version])


class Changes:
    def __init__(self):
        self._entries = []
        self._binnmus = []
        self.sorted = True
        self.reversed = False

    def __add__(self, other):
        if self.__class__ != other.__class__:
            raise ValueError("Can only add Changes to another Changes")
        added = Changes()
        added._entries.extend(self._entries)
        added._entries.extend(e for e in other._entries
                              if e not in added._entries)
        added._binnmus.extend(self._binnmus)
        added._binnmus.extend(b for b in other._binnmus
                              if b not in added._binnmus)
        added.sorted = False
        return added

    def __iadd__(self, other):
        if self.__class__ != other.__class__:
            raise ValueError("Can only add Changes to another Changes")
        self._entries.extend(e for e in other._entries
                             if e not in self._entries)
        self._binnmus.extend(b for b in other._binnmus
                             if b not in self._binnmus)
        self.sorted = False
        return self

    def sort(self):
        if self.sorted:
            return
        self._entries.sort(key=EntrySorter(self._entries).key_func,
                           reverse=self.reversed)
        self._binnmus.sort(key=EntrySorter(self._binnmus).key_func,
                           reverse=self.reversed)
        self.sorted = True

    @property
    def entries(self):
        self.sort()
        return self._entries

    @property
    def binnmus(self):
        self.sort()
        return self._binnmus

    @property
    def changes(self):
        if self.entries:
            return '\n\n'.join(map(str, self.entries)) + '\n'
        return ''

    def save_entry(self, entry):
        self.sorted = False
        if entry.binnmu:
            self._binnmus.append(entry)
        else:
            self._entries.append(entry)

    def reverse(self):
        self.reversed = True
        self.sorted = False


class NullFilterer:
    def __init__(self):
        pass

    def reset(self):
        pass

    def stop(self, _entry):
        return False

    def filter(self, _entry):
        return False


class ChangelogParser:
    _changelog_header = re.compile(
        r'^(?P<package>\S+) \((?P<version>.*)\) .*;.*urgency=(?P<urgency>\w+)')
    _changelog_header_ancient = re.compile(
        r'(^\S+ \(?\d.*\)|Old Changelog:|Changes|ChangeLog begins|'
        r'Mon|Tue|Wed|Thu|Fri|Sat|Sun)')
    _changelog_header_emacs = re.compile(r'(;;\s*)?Local\s+variables.*',
                                         re.IGNORECASE)
    _changelog_trailer = re.compile(r'^\s--\s.*<.*@.*>.*$')
    _binnmu_marker = 'binary-only=yes'

    def __init__(self, package, source, filterer):
        '''See comment above Filterer class in apt_listchanges.py for
        documentation of filterer'''
        self._package = package
        self._source = source
        self._changes = Changes()
        self._filterer = filterer or NullFilterer()
        self._stopped = False

    def parse(self, path, fd):
        '''Parse changelog or news from the given file descriptor.'''
        ancient = False
        entry = None
        is_debian_changelog = False

        self._filterer.reset()
        for line in fd.readlines():
            line = line.decode('utf-8', 'replace')

            if line.startswith('#'):
                continue

            if entry is not None and (line.startswith(' ') or line == '\n'):
                if not ancient and self._changelog_trailer.match(line):
                    entry.set_trailer(line)
                    go_on = self._save_entry(entry)
                    entry = None
                    if not go_on:
                        break
                else:
                    entry.add_content(line)
            else:
                match = self._changelog_header.match(line) \
                      if not ancient else None
                if match:
                    is_debian_changelog = True
                    version = match.group('version')
                    if not self._save_entry(entry):
                        entry = None
                        break
                    entry = ChangelogEntry(
                        line, path, match.group('package'), self._source,
                        version, match.group('urgency'),
                        self._binnmu_marker in line)

                elif self._changelog_header_ancient.match(line):
                    if not is_debian_changelog:
                        # probably upstream changelog in GNU format
                        break
                    ancient = True
                    if not self._save_entry(entry):
                        entry = None
                        break
                    entry = ChangelogEntry(line, path, self._package,
                                           self._source, '', 'low', False)

                elif self._changelog_header_emacs.match(line):
                    break

                elif entry:
                    entry.add_content(line)
                    continue

                # If we get this far we're in between entries, nothing to do

        self._save_entry(entry)

        return self._changes if is_debian_changelog else None

    def _save_entry(self, entry):
        if self._stopped:
            # This should never happen because the function that calls this
            # should stop after the first time we return False, but we've got
            # this here just in case.
            return False
        if self._filterer.stop(entry):
            self._stopped = True
            return False
        if entry and not self._filterer.filter(entry):
            self._changes.save_entry(entry)
        return True


class ChangelogsReader:
    def __init__(self, package, source, rootdir, filterer):
        self._package = package
        self._source = source
        self._rootdir = rootdir
        if rootdir.endswith('/'):
            self.prefix_len = len(rootdir)
        else:
            self.prefix_len = len(rootdir) + 1
        self._filterer = filterer

    def _find_first(self, filenames):
        for filename in (filenames or []):
            result = self._read_changelog(filename)
            if result:
                return result
        return None

    def read_changelogs(self, filenames, binnmus_filenames):
        return (self._find_first(binnmus_filenames) or
                self._find_first(filenames))

    def _read_changelog(self, fileglob):
        filename, fd = self._open_changelog_file(
            os.path.join(self._rootdir, fileglob))
        if not filename:
            return False
        filename = filename[self.prefix_len:]

        with fd:
            return ChangelogParser(self._package, self._source,
                                   self._filterer).parse(filename, fd)

    def _open_changelog_file(self, filename_glob):
        filenames = glob.glob(filename_glob)

        for filename in filenames:
            try:
                if os.path.isdir(filename):
                    ALCLog.error(
                        _("Ignoring `%s' (seems to be a directory!)") %
                        filename)
                elif filename.endswith('.gz'):
                    return filename, gzip.GzipFile(filename)
                else:
                    return filename, open(filename, 'rb')
                break
            except IOError as e:
                if e.errno not in (errno.ENOENT, errno.ELOOP):
                    raise
        return None, None


def _changelog_variations(filename):
    formats = ['usr/share/doc/*/%s.gz',
               'usr/share/doc/*/%s']
    return [x % filename for x in formats]


class Package:
    news_filenames = _changelog_variations('NEWS.Debian')
    changelog_filenames = (
        _changelog_variations('changelog.Debian') +
        _changelog_variations('changelog'))

    def __init__(self, path, filterer):
        self.path = path
        self.filterer = filterer

        parser = ControlParser()
        parser.readdeb(self.path)
        pkgdata = parser.stanzas[0]

        self.binary = pkgdata.Package
        self.source = pkgdata.source
        self.Version = pkgdata.version
        self.arch = pkgdata.Architecture

    def __str__(self):
        return f'<{self.__class__.__qualname__} object for {self.path}>'
    __repr__ = __str__

    def extract_changes(self, which, filterer=None):
        '''Extract changelog and binnmu entries, news or both from the package.

        Unpacks changelog or news files from the binary package, and parses
        them.
        If filterer is specified, it overrides the one specified on object
        creation.
        '''
        ALCLog.debug(_("Extracting changes from %(debfile)s") %
                     {'debfile': self.path})
        news_filenames = []
        changelog_filenames = []
        binnmu_filenames = []
        if which in ('both', 'news'):
            news_filenames = self.news_filenames
        if which in ('both', 'changelogs'):
            changelog_filenames = self.changelog_filenames
            binnmu_filenames = \
                _changelog_variations('changelog.Debian.' + self.arch)

        filenames = news_filenames + changelog_filenames + binnmu_filenames

        tempdir = self._extract_contents(filenames)
        try:
            reader = ChangelogsReader(
                self.binary, self.source, tempdir,
                filterer or self.filterer)

            if news_filenames:
                news = reader.read_changelogs(self.news_filenames, None)
            else:
                news = None
            if changelog_filenames:
                changelog = reader.read_changelogs(
                    changelog_filenames, binnmu_filenames)
            else:
                changelog = None

        finally:
            shutil.rmtree(tempdir, 1)

        return (news, changelog)

    @staticmethod
    def fn_pattern_match(filenames, patterns):
        return [f for f in filenames
                if any(fnmatch.fnmatch(f, p) for p in patterns)]

    def extract_changes_via_installed(self, which, filterer=None):
        '''Like extract_changes but reads already installed changelog files'''
        ALCLog.debug(_("Extracting installed changes for %(package)s") %
                     {'package': self.binary})
        news_files = []
        changelog_files = []
        binnmu_files = []
        if which in ('both', 'news'):
            news_files = self.news_filenames
        if which in ('both', 'changelogs'):
            changelog_files = self.changelog_filenames
            binnmu_files = \
                _changelog_variations('changelog.Debian.' + self.arch)
        package_files = self._extract_filenames(
            news_files + changelog_files + binnmu_files)
        news_files = self.fn_pattern_match(package_files, news_files)
        changelog_files = self.fn_pattern_match(package_files, changelog_files)
        binnmu_files = self.fn_pattern_match(package_files, binnmu_files)

        reader = ChangelogsReader(
            self.binary, self.source, '/',
            filterer or self.filterer)

        if news_files:
            news = reader.read_changelogs(news_files, None)
        else:
            news = None
        if changelog_files:
            changelog = reader.read_changelogs(
                changelog_files, binnmu_files)
        else:
            changelog = None

        return (news, changelog)

    def extract_changes_via_apt(self, filterer=None):
        '''Run apt-get changelog and parse the downloaded changelog.
        Retrieve changelog using the "apt-get changelog" command, and parse it.
        '''
        # Retrieve changelog file and save it in a temporary directory
        tempdir = tempfile.mkdtemp(prefix='apt-listchanges')
        changelog_file = f'network/{self.binary}'
        os.mkdir(os.path.join(tempdir, os.path.dirname(changelog_file)))
        with open(os.path.join(tempdir, changelog_file), 'wb') as changelog_fd:
            try:
                command = ['apt-get', '-qq', 'changelog',
                           f'{self.binary}={self.Version}']
                ALCLog.debug(_("Calling %(cmd)s to retrieve changelog") %
                             {'cmd': str(command)})
                subprocess.run(
                    command, stdout=changelog_fd,
                    stderr=subprocess.PIPE, timeout=120, check=True)

            except subprocess.CalledProcessError as ex:
                ALCLog.error(
                    _('Unable to retrieve changelog for package %(pkg)s; '
                      + "'apt-get changelog' failed with: %(errmsg)s")
                    % {'pkg': self.binary,
                       'errmsg': ex.stderr.decode('utf-8', 'replace')
                       if ex.stderr else str(ex)})

            except Exception as ex:
                ALCLog.error(
                    _('Unable to retrieve changelog for package %(pkg)s; '
                      + "could not run 'apt-get changelog': %(errmsg)s")
                    % {'pkg': self.binary, 'errmsg': str(ex)})

            else:
                return ChangelogsReader(
                    self.binary, self.source, tempdir,
                    filterer or self.filterer).read_changelogs(
                        [changelog_file], None)

            finally:
                changelog_fd.close()
                shutil.rmtree(tempdir, 1)

        return None

    def _extract_filenames(self, patterns):
        qpath = shlex.quote(self.path)
        qnames = ' '.join([shlex.quote('./' + x) for x in patterns])
        extract_command = (
            f'dpkg-deb --fsys-tarfile {qpath} | '
            f'tar tf - --wildcards {qnames} 2>/dev/null')
        result = subprocess.run(
            extract_command, shell=True, capture_output=True, encoding='utf-8',
            check=False)
        # Is this really necessary? It seems to me that ctrl-C would also
        # interrupt the apt-listchanges process. :shrug: - jik 2023-10-01
        if result.returncode == -signal.SIGINT:
            raise KeyboardInterrupt
        return list(fn[2:] for fn in result.stdout.strip().split('\n'))

    def _extract_contents(self, filenames):
        tempdir = tempfile.mkdtemp(prefix='apt-listchanges')

        qpath = shlex.quote(self.path)
        qdir = shlex.quote(tempdir)
        qnames = ' '.join([shlex.quote('./' + x) for x in filenames])
        extract_command = (
            f'dpkg-deb --fsys-tarfile {qpath} | '
            f'tar xf - --wildcards -C {qdir} {qnames} 2>/dev/null')

        # tar exits unsuccessfully if _any_ of the files we wanted
        # were not available, so we can't do much with its status
        status = os.system(extract_command)

        if os.WIFSIGNALED(status) and os.WTERMSIG(status) == signal.SIGINT:
            shutil.rmtree(tempdir, 1)
            raise KeyboardInterrupt

        return tempdir
