Release new version 0.7.1
[grml-x.git] / grml-x
diff --git a/grml-x b/grml-x
index 64d910e..b180e4d 100755 (executable)
--- a/grml-x
+++ b/grml-x
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/python3
 # -*- coding: utf-8 -*-
 # vim: set et ts=4:
 
@@ -9,7 +9,7 @@
 # License:       This file is licensed under the GPL v2.
 ###############################################################################
 
-import os, subprocess, sys, tempfile, time, traceback
+import fileinput, os, subprocess, sys, tempfile, time, traceback
 from optparse import OptionParser
 
 class Section(object):
@@ -24,6 +24,8 @@ class Section(object):
             v = self.data[k]
             if isinstance(v, list):
                 v = '" "'.join(v)
+            elif not isinstance(v, str): # int, others
+                v = str(v)
             elif '-' in v: # sync range
                 pass
             else:
@@ -61,16 +63,16 @@ def build_bootparams():
                     lines.extend(f.readlines())
                     f.close()
         except:
-            print 'W: Error while getting bootparams from %s' % p
+            print('W: Error while getting bootparams from %s' % p)
     f = open('/proc/cmdline')
     lines.append(f.readline())
     f.close()
-    walk_bootparams_path('/cdrom/bootparams')
-    walk_bootparams_path('/live/image/bootparams')
+    walk_bootparams_path('/lib/live/mount/medium/bootparams')
+    walk_bootparams_path('/run/live/medium/bootparams')
     params = {}
     for p in ' '.join(lines).split(' '):
         if '=' in p:
-            (k,v) = p.split('=', 2)
+            (k,v) = p.split('=', 1)
             params[k] = v
         else:
             params[p] = True
@@ -106,6 +108,20 @@ def which(program):
 
     return None
 
+XORG_CONF_HEADER = "# Automatically generated by grml-x."
+def check_old_xorg_conf(filename, overwrite):
+    # True: no problem, we can create/overwrite the config file
+    # False: pre-existing config file, and we are not to overwrite it
+    if overwrite: return True
+    if not os.path.exists(filename): return True
+    try:
+        f = file(filename, 'r')
+        lines = f.readlines()
+        f.close()
+        return (not XORG_CONF_HEADER in lines)
+    except IOError:
+        return False
+
 parser = OptionParser(usage="usage: %prog [options] [window-manager]")
 parser.add_option("--nostart", action="store_false", dest="start_server", default=True,
                 help="Don't start X server")
@@ -128,17 +144,14 @@ def main():
     (options, args) = parser.parse_args()
     bootparams = build_bootparams()
 
-    if os.getuid() == 0:
-        print "W: running as root is unsupported and may not work."
+    if os.getuid() == 0 and options.start_server:
+        print("W: running as root is unsupported and may not work.")
         time.sleep(1)
 
-    if os.path.exists(options.xorg_conf):
-        if options.overwrite:
-            os.unlink(options.xorg_conf)
-        else:
-            print "E: Not overwriting existing %r without --force." % options.xorg_conf
-            print "I: If you previously ran grml-x, use startx /usr/bin/x-window-manager"
-            return 1
+    if not check_old_xorg_conf(options.xorg_conf, options.overwrite):
+        print("E: Not overwriting existing %r without --force." % options.xorg_conf)
+        print("I: If you previously ran grml-x, use startx /usr/bin/x-window-manager")
+        return 1
 
     if 'xmode' in bootparams and not options.mode: options.mode = bootparams['xmode']
     if 'xmodule' in bootparams and not options.module: options.module = bootparams['xmodule']
@@ -160,44 +173,54 @@ def main():
         for depth in [8, 15, 16, 24, 32]:
             screen.subsect += "SubSection \"Display\"\n\tDepth %d\n\tModes \"%s\"\t\nEndSubSection\n" % (depth, options.mode)
 
-    if len(args) == 1:
-        window_manager = args[0]
-        wm_path = which(window_manager)
-        if not wm_path:
-            print "E: Cannot find window manager %r, aborting." % window_manager
-            return 2
-        run_program(["sudo", "update-alternatives", "--set", "x-window-manager", wm_path])
-
-    config_empty = True
-    if monitor or device or len(screen.data) > 0 or screen.subsect != '':
-        config_empty = False
+    xinitrc = '~/.xinitrc'
+    if 'XINITRC' in os.environ: xinitrc = os.environ['XINITRC']
+    xinitrc = os.path.expanduser(xinitrc)
+
+    window_manager = 'x-window-manager'
+    if len(args) == 1: window_manager = args[0]
+    window_manager_path = which(window_manager)
+    if not window_manager_path:
+        print("E: Cannot find window manager %r, aborting." % window_manager)
+        return 2
+
+    wm_exec = "exec %s\n" % window_manager_path
+    if not os.path.exists(xinitrc):
+        f = open(xinitrc, 'w')
+        f.write("#!/bin/sh\n")
+        f.write(wm_exec)
+        f.close()
+    else:
+        f = open(xinitrc, 'r')
+        lines = f.readlines()
+        f.close()
+        f = open(xinitrc, 'w')
+        for line in lines:
+            if line.strip().startswith('exec '): line = wm_exec
+            f.write(line)
+        os.fchmod(f.fileno(), 0o750)
+        f.close()
 
     # write new config
-    if not config_empty:
+    if monitor or device or len(screen.data) > 0 or screen.subsect != '':
         try:
             f = tempfile.NamedTemporaryFile(delete=False)
-            f.write('# Automatically generated by grml-x.\n')
-            f.write('# See man xorg.conf or /etc/X11/xorg.conf.example for more\n')
+            f.write(XORG_CONF_HEADER + "\n")
+            f.write("# DO NOT MODIFY, YOUR CHANGES WILL BE LOST - OR REMOVE ALL HEADER LINES\n")
+            f.write("# See man xorg.conf or /etc/X11/xorg.conf.example for more\n")
             if monitor: f.write(str(monitor))
             if device: f.write(str(device))
             f.write(str(screen))
             f.flush()
+            os.fchmod(f.fileno(), 0o644)
             run_program(['sudo', 'mv', '-f', f.name, options.xorg_conf])
         finally:
             f.close()
 
     if options.start_server:
-        xinitrc = '~/.xinitrc'
-        if 'XINITRC' in os.environ: xinitrc = os.environ['XINITRC']
-        xinitrc = os.path.expanduser(xinitrc)
-        startx = ['startx']
-        if os.path.exists(xinitrc):
-            startx.append(xinitrc)
-        else:
-            startx.append(which('x-window-manager'))
-        startx.append('--')
+        startx = ['startx', xinitrc, '--']
         if options.display: startx.append(':' + options.display)
-        print "Starting X: %r" % startx
+        print("Starting X: %r" % startx)
         run_program(startx)
 
     return 0
@@ -207,7 +230,7 @@ if __name__ == '__main__':
     try:
         rc = main()
     except Exception:
-        print "E: Exception: ",
+        print("E: Exception: ", end=' ')
         traceback.print_exc()
     sys.exit(1)