#!/usr/bin/python
# vim:ts=4 sw=4 tw=80
#
# siloconf -- check / update silo.conf
#
# (C) 2007 Emanuele Rocca <ema@debian.org>

__revision__ = "20070812"

import os
import re
from sys import argv, exit

def usage():
    print "Usage: siloconf [ check | update ]"

class SiloConf(object):

    def __init__(self, filename='/etc/silo.conf'):
        fd = open(filename, 'r')
        self.lines = [ l.lstrip().rstrip(' \n') for l in fd.readlines() ]
        fd.close()
        
        self.filename = filename
        self.labels, self.images, self.initrds = [], [], []
        self.default = ''

        for line in self.lines:
            if line.startswith('label'):
                self.labels.append(line.replace("label=", ""))
            elif line.startswith('image'):
                self.images.append(line.replace("image=", ""))
            elif line.startswith('initrd'):
                self.initrds.append(line.replace("initrd=", ""))
            elif line.startswith('default'):
                self.default = line.replace('default=', '')

    def __str__(self):
        output = "Filename: \n\t%s\n" % self.filename

        output += "Kernel images:\n"
        for img in self.images:
            output += "\t%s\n" % img

        output += "Initrd images:\n"
        for img in self.initrds:
            output += "\t%s\n" % img
        
        if self.default:
            output += "Default: %s\n" % self.default

        return output
    
class SiloConfChecker(SiloConf):
    
    def checkfiles(self):
        for filename in self.images + self.initrds:
            if not os.path.isfile(filename):
                print "E: cannot find", filename, "!"

    def checkdefault(self):
        if self.default not in self.labels:
            print "E: default label %s not found" % self.default

class SiloConfUpdater(SiloConf):

    filere = re.compile("(config|vmlinuz|initrd.img)-.*")
    
    def buildconf(self):
        """
        image=/boot/vmlinuz-2.6.23-rc2 
            label=2.6.23-rc2
            initrd=/boot/initrd.img-2.6.23-rc2
        """

        for f in os.listdir('/boot'):
            if f.startswith('vmlinuz-') and '/boot/' + f not in self.images:
                version = f.replace('vmlinuz-', '')
                print "image=/boot/%s" % f
                print "\tlabel=%s" % version
                print "\tinitrd=/boot/initrd.img-%s\n" % version

if __name__ == "__main__":
    try:
        arg = argv[1]
    except IndexError:
        usage()
        exit(1)

    if arg == "check":
        checker = SiloConfChecker()

        checker.checkfiles()
        if checker.default:
            checker.checkdefault()

    elif arg == "update":
        updater = SiloConfUpdater()
        updater.buildconf()

    else:
        usage()
