#!/usr/bin/python
# -*- Mode: Python; indent-tabs-mode: nil; tab-width: 4 -*-
#
# Copyright 2010 Canonical Ltd
# Authors:
#   Mike Carifio <michael.carifio@canonical.com>
#   Michael Terry <michael.terry@canonical.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.

import os, re
import logging
logging.basicConfig(level=logging.INFO)


def handle_reboot():
    # now do the reboot logic
    windows_title_prefix = "Windows 7"
    reboot_title = extract_full_title(windows_title_prefix, "/boot/grub/grub.cfg")
    if reboot_title:
        logging.info("Rebooting '%s'" % (reboot_title))
        os.system('grub-reboot ' + reboot_title)
        os.system('reboot')


def extract_full_title(prefix, boot_cfg):
    """Given a boot.cfg menuitem string prefix, return the entire menu item with leading and trailing quotes

    Suppose /boot/grub/grub.cfg contains:
       .
       .
       .
    menuentry "Windows 7 (loader) (on /dev/sda1)" {
       .
       .
       .
    }

    then extract_full_title(r'Window 7 \(loader\'), r'/boot/grub/grub.cfg')
       #=> '"Windows 7 (loader) (on /dev/sda1)"'
    Note that the quotes are included in the returned value"""


    contents = file(boot_cfg).read()
    pattern = r'menuentry ("' + prefix + r'[^"]*")'
    match = re.search(pattern, contents)
    if match:
        return match.group(1)
    else:
        logging.warn("Can't locate menuentry '%s' in file '%s'" % (prefix, boot_cfg))
        # TODO mcarifio: what should we do if the menuitem isn't there? Right now I return nothing.
        return ''


if __name__ == "__main__":
    #support for command line options
    import optparse
    parser = optparse.OptionParser()

    #set the logging level to show debug messages
    parser.add_option("-v", "--verbose", action="store_true",
                      dest="verbose", help="Show debug messages")

    (options, args) = parser.parse_args()

    # Up logging if verbose.
    if options.verbose:
      logging.basicConfig(level=logging.DEBUG)
      logging.debug('Debug logging enabled')

    #run the application
    handle_reboot()
