#!/usr/bin/python
#
# This script checks status of configuration files after upgrade.
# Current checks are:
#    - Obsolete config files
#    - Existence of *.dpkg-dist files. It means there was a prompt for an
#    unmodified configuration during upgrade
#
# (C) 2012 Canonical Ltd.
# Author: Jean-Baptiste Lallement <jean-baptiste.lallement@canonical.com>
# License: GPL v2 or higher

import unittest
import subprocess
import glob

class TestConfFiles(unittest.TestCase):
    def test_obsolete_configfile(self):
        '''Check for obsolete config files after upgrade'''
        cmd = ['dpkg-query' ,'-W', '-f=${Package}\n${Conffiles}\n\n']
        #output_file = '/var/log/dist-upgrade/obsolete_conffiles.log'
        output_file = '/tmp/obsolete_conffiles.log'
        test_output = ''

        dpkgquery = subprocess.check_output(cmd)
        current = set()
        obsolete = {}
        for pkg in dpkgquery.split('\n\n'):
            pkg = pkg.strip().split('\n')
            pkgname = pkg[0]
            cfgfiles = pkg[1:]
            for cfgfile in cfgfiles:
                cfgbits = cfgfile.strip().split()
                if len(cfgbits) < 3:
                    # No status, not obsolete
                    current.add(cfgbits[0])
                else:
                    file, md5, status = cfgbits[:3]
                    if 'obsolete' in status:
                        obsolete.setdefault(pkgname, []).append(file)
                    else:
                        current.add(file)

        for pkgname in sorted(obsolete.keys()):
            cfgfiles = [cfgfile for cfgfile in obsolete[pkgname]
                        if cfgfile not in current]
            if cfgfiles:
                test_output += "%s\n  %s\n" % (pkgname, "\n  ".join(cfgfiles))

        if test_output:
            with open(output_file, 'w') as f:
                print >>f, test_output

    def test_dpkgdist(self):
        '''Check for existence of *.dpkg-dist files'''
        whitelist_dpkg = [
                          '/tmp/sudoers.dpkg-dist',
                          '/tmp/release-upgrades.dpkg-dist' ]

        cmd = ['find /etc -name "*.dpkg-dist" -exec cp \'{}\' /tmp \;']
        subprocess.check_call(cmd, shell=True)

        dpkgdist_files = glob.glob('/tmp/*.dpkg-dist')
        dpkgdist_files = [ f for f in dpkgdist_files if f not in whitelist_dpkg]

        self.assertEqual(
            len(dpkgdist_files), 0,
            "*.dpkg-dist files found after upgrade:\n  %s" %
            "\n  ".join(dpkgdist_files))

if __name__ == '__main__':
    unittest.main()
