Source

vasm / src / vasm / backend / bootmode.py

#!/usr/bin/env python

#    This file is part of VASM.
#
#    VASM is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License v3 as published by
#    the Free Software Foundation.
#
#    VASM 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 VASM.  If not, see <http://www.gnu.org/licenses/>.

__author__ = "Moises Henriquez"
__author_email__ = "moc.liamg@xnl.E0M"[::-1]

""" Support module for bootmode.py.
Contains methods for setting and checking the VL boot (/etc/inittab) settings
"""

class InitTab(object):
    def __init__(self, fopath="/etc/inittab"):
        self.path = fopath
    
    def getMode(self):
        """ Return the current boot mode."""
        with open(self.path) as f:
            for line in f:
                if self._line_sets_default_mode(line):
                    return int(line.split(":")[1])
    
    def setMode(self, init_value):
        """ Set the default boot mode to the new init_value.
        Boot mode cannot be set to 0 or 6 because these values
        will cause an endless boot loop."""
        # avoid values 0 and 6
        assert init_value not in (0, 6), "Default boot mode cannot be 0 or 6"
        
        newdata = []
        with open(self.path) as fo:
            for line in fo:
                if self._line_sets_default_mode(line):
                    line = "id:%s:initdefault:\n" % init_value
                newdata.append(line)
                
        # write the changes to the file.
        # DO NOT catch exceptions on this type of operations because
        # we need to know what is going wrong (if anything)
        fo = open(self.path, "w")
        with fo as f:
            f.writelines("".join(newdata))
        fo.close()
    
    def _line_sets_default_mode(self, line):
        """ Returns tru if line sets the default mode """
        return line.startswith("id:") and "initdefault:" in line