~tinarussell/tinasplash/trunk

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
#!/usr/bin/python
# Code by Tina

import fileinput
import os
import os.path
import sys
import glob
import commands
import shutil
from linecache import *

class FlagrantError(Exception):
    """A class for program-defined errors.
    The term "Flagrant Error" comes from
    "Homestar Runner." """
    def __init__(string):
        if string == "menulst":
            print "Cannot find menu.lst"

def findMenuLst():
    """Find menu.lst from a list of likely paths."""
    if os.path.exists("/boot/grub/menu.lst"):
        return "/boot/grub/menu.lst"
    if os.path.exists("/boot/menu.lst"):
        return "/boot/menu.lst"
    else:
        raise FlagrantError("menulst")

#Assign names to locations of related files.

myPath = os.path.dirname(os.path.join(os.getcwd(), sys.modules[__name__].__file__)) + "/"
grubPath = os.path.dirname(findMenuLst()) + "/"
splashPath = grubPath + "splashimages/" #This is the default splashimages directory.
backupPath = grubPath + "backup/"

madeBackup = 0

def findLine(path, phrase, nocomment = 0, phraseAtBeginning = 0, backwards = \
0, startline = 0, endline = -1, returnLine = 0, endphrase = None,
endphraseAtBeginning = 0):
    """Searches for a specific phrase in a given text file.
    If the phrase is found, this function returns the line that it's on.
    If the phrase is not found, this function returns -1.
    If nocomment is not zero, then the function will skip any instance
    of the phrase on a line in which a pound sign (#) appears before it.
    If "phraseAtBeginning" is not zero, then a "find" will only count if the
    phrase is at the very beginning of the line, not including spaces.
    If "backwards" is not zero, then the function will search backwards from
    the "startline."
    "Startline" defines a starting point, for a forwards or backwards search.
    (If "backwards" is nonzero and "startline" is zero, this function will
    search only the first line.)
    "endline" defines and ending point. "-1" means "until the end of the file,"
    which is the default.
    If "returnLine" is not zero, then this function will return the line found,
    as a string, rather than its location.
    "endphrase" defines a phrase that will indicate the last line you wish to
    search on.
    "endPhraseAtBeginning" means that the "endphrase" only counts if it's at
    the beginning of a line, not including spaces."""
    relFile = open(path)
    lineList = relFile.readlines()
    relFile.close()
    dontBreak = 1
    foundIt = 0
    i = startline
    limit = len(lineList)
    while (i < limit) & (foundIt == 0) & (i >= 0) & (dontBreak == 1):
        currentLine = lineList[i]
        if phrase in currentLine:
            if nocomment == 0:
                foundIt = 1
            else:
                if "#" in currentLine:
                    poundLoc = currentLine.find("#")
                    phraseLoc = currentLine.find(phrase)
                    arbiter = poundLoc - phraseLoc
                    if arbiter > 0:
                        foundIt = 1
                else:
                    foundIt = 1
        if type(endphrase) == type("str"):
            if endphrase in currentLine:
                if endphraseAtBeginning == 0:
                    dontBreak = 0
                else:
                    if currentLine.strip().find(endphrase) == 0:
                        dontBreak = 0
        if endline >= 0:
            if i == endline:
                dontBreak = 0
        jedi = i
        if backwards == 0:
            i += 1
        else:
            i -= 1
        if (foundIt == 1) & (phraseAtBeginning != 0):
            if currentLine.strip().find(phrase) != 0:
                foundIt = 0
    if foundIt == 1:
        if returnLine != 0:
            return currentLine
        else:
            return jedi
    else:
        return -1

def writeToFile(path, line, phrase, append = 0):
    """Replace one line, specified by number "line", in the file specified by
    string "path", with a line specified by string "phrase." If "append" is not
    zero, than you will simply be adding one line after the specified location."""
    relFile = open(path)
    backupInLines = relFile.readlines()
    relFile.close()
    if append == 0:
        backupInLines[line] = phrase + "\n"
    else:
        backupInLines[line] += phrase + "\n\n"
    relFile = open(path, "w")
    relFile.writelines(backupInLines)
    relFile.close

def replaceSplash(path):
    """Find the location of the splashimage setting in menu.lst and change it."""
    backupMenuLst()
    menulst = findMenuLst()
    splashLine = findLine(menulst, "splashimage", 1)
    if splashLine == -1:
        colorsLine = findLine(menulst, "color")
        insertLine = colorsLine + 1
        writeToFile(menulst, insertLine, "splashimage=" + getRootDev() + path, 1)
    else:
        writeToFile(menulst, splashLine, "splashimage=" + getRootDev() + path)

def getFileList(path, ext):
    """For a specified directory and extension, return a list of strings naming
    each file whose name ends in the specified extension."""
    if os.path.exists(path) != True:
        os.mkdir(path)
    fileList = glob.glob(os.path.normpath(path + "/*." + ext))
    return fileList

def gzipExtractToTmp(path):
    """Extract a gzip file to a temporary directory, and return the location
    of the resulting file."""
    if os.path.exists(splashPath + "tmp") != True:
        os.mkdir(splashPath + "tmp")
    tmpPathG = splashPath + "tmp/" + os.path.basename(path)
    tmpPath = tmpPathG.strip(".gz")
    if os.path.exists(tmpPath) != True:
        shutil.copy(path, tmpPathG)
        commands.getoutput("gzip -d " + tmpPathG)
    return tmpPath

def clearTmp():
    """Delete all created temporary files ending in "xpm," in preparation for
    the program shutting down. Called by "closeUpShop()" in "tinasplash.py"."""
    commands.getoutput("rm " + splashPath + "tmp/*.xpm")

def getRootDev(deb=0):
    """Find the root device in GRUB "(hd#,#)" notation. If "deb" is zero, the
    default, this function will check the currently-running kernel name with
    "uname -r", look for the first instance of that kernel in the menu.lst
    options, and return the location of its root partition. If "deb" is not
    zero, then it will use the alternate method of checking the Debian (also
    found in Ubuntu and other Debian-based distros) kernel list settings in
    menu.lst and returning the default GRUB root location."""
    menu = "/home/tina/code/python/projects/tinasplash/testmenu.lst"
    if deb != 0:
        debRoot = getDebRoot(menu)
        if debRoot != False:
            return debRoot
    kernelName = commands.getoutput("uname -r")
    kernelNameLoc = findLine(menu, kernelName, 1)
    titleLoc = findLine(menu, "title", 0, 1, 1, kernelNameLoc)
    rootLine = findLine(menu, "root", 0, 1, 0, titleLoc + 1, -1, 1, "title", 1)
    if rootLine == -1:
        rootLine = findLine(menu, "kernel", 0, 1, 0, titleLoc + 1, -1, 1, "title", 1)
    rootDevStart = rootLine.find("(")
    rootDevEnd = rootLine.find(")") + 1
    rootDev = rootLine[rootDevStart:rootDevEnd]
    return rootDev

def getDebRoot(menu):
    """Called by getRootDev(). Finds the default GRUB root device by looking
    in the settings for the Debian automatic kernel list."""
    defaultOptionsBegin = findLine(menu, "## ## Start Default Options ##")
    rootLine = findLine(menu, "# groot=", 0, 1, 0, defaultOptionsBegin, -1, \
    1, "## ## End Default Options ##", 1)
    if rootLine == -1:
        return False
    rootDevStart = rootLine.find("(")
    rootDevEnd = rootLine.find(")") + 1
    rootDev = rootLine[rootDevStart:rootDevEnd]
    return rootDev

def backupMenuLst():
    global madeBackup
    global backupPath
    if madeBackup == 0:
        if os.path.exists(backupPath) != True:
            os.mkdir(backupPath)
        dontBreak = 0
        i = 8
        if os.path.exists(backupPath + "/menu.lst.backup9"):
            os.remove(backupPath + "/menu.lst.backup9")
        while i >= 0:
            if os.path.exists(backupPath + "/menu.lst.backup" + str(i)):
                shutil.move(backupPath + "/menu.lst.backup" + str(i), backupPath \
                + "/menu.lst.backup" + str(i+1))
            i -= 1
        shutil.copy(findMenuLst(), backupPath + "/menu.lst.backup0")
        madeBackup = 1