# -*- coding: utf-8 -*-

# burnlib/interactive_configure.py
#
# Copyright © 2009 Ben Finney <ben+python@benfinney.id.au>.
# Copyright © 2004–2009 Gaetano Paolone <bigpaul@hacknight.org>.
#
# 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; either version 2
# of the License, or (at your option) any later version.
#
# 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA.

""" Interactive configuration for ‘burn’.

    main()
        Generates the ‘burn’ configuration file, from defaults and via
        interactive console dialogue.

    """

import sys
import os
import os.path
import gettext
import optparse
import pwd
import textwrap

import burnlib.version
import configure
import console
import device


#gettext
gettext.bindtextdomain('burn_configure', '/usr/share/locale/it/LC_MESSAGES/')
gettext.textdomain('burn_configure')
_ = gettext.gettext


class OptionParser(optparse.OptionParser, object):
    """ Command-line parser for this program. """

    default_program_name = "burn-configure"

    default_usage = "%prog [options]"

    default_description = _(
        "Generate configuration for Burn.")

    default_epilog = _(
        "This tool reads the default configuration from a template,"
        " queries interactively for settings specific to this system,"
        " then generates the configuration for Burn"
        " (Burn until recorded, now!) to a new file.")

    def __init__(
        self,
        prog=default_program_name,
        version=burnlib.version.version,
        usage=default_usage,
        description=default_description,
        epilog=default_epilog,
        *args, **kwargs):
        super(OptionParser, self).__init__(
            prog=prog, version=version,
            usage=usage, description=description, epilog=epilog,
            *args, **kwargs)

        self.add_option(
            "-t", "--template-file",
            action='store', dest='template_file_path',
            default="/usr/share/burn/example/burn.conf",
            metavar="PATH", help=_(
                "Read the configuration template from file PATH"
                " (default '%default')."))
        self.add_option(
            "-o", "--output-file",
            action='store', dest='output_file_path',
            default="burn.conf.new",
            metavar="PATH", help=_(
                "Write the generated configuration to file PATH"
                " (default '%default')."))

    def check_values(self, values, args):
        """ Check the parsed values and arguments. """
        max_args = 0
        if len(args) > max_args:
            args_text = " ".join(args)
            message = _("unexpected arguments: %(args_text)s") % vars()
            self.error(message)

        return (values, args)


def prog_intro(path):
    """ Introductive program output. Also checks if superuser. """
    print _(
        'Burn-configure v.%(version)s'
        + '  Written by %(author_name)s.') % vars(burnlib.version)
    print _(
        'This tool helps writing configuration file for'
        ' burn - Burn until recorded, now!')
    print _(
        'This software comes with absolutely no warranty!'
        ' Use at your own risk!')
    print _('Burn-configure is free software.')
    print _('See software updates at <URL:%(_url)s>.') % vars(burnlib)
    print
    print _('This utility will generate: '), path
    print _('Place this file as ~/.burnrc or /etc/burn.conf .')
    print
    print
    if not pwd.getpwuid(os.geteuid())[0] == "root":
        print _('You are not superuser (root).')
        print _(
            'You can still go through this configuration process'
            ' but remember that you should be root (or have permissions'
            ' on programs and devices) in order to use burn.')
        if not console.ask_yesno(
            _('Continue without superuser privilege'), True):
            sys.exit()


def giveme_realpath(path):
    """ Checks if path exists and return absolute path. """
    if os.path.exists(path):
        if os.path.islink(path):
            return os.path.realpath(path)


def main():
    """ Mainline routine for the burn-configure program. """

    option_parser = OptionParser()
    (options, args) = option_parser.parse_args()

    #Checking if there is a configuration file generated by this program
    target_conf_file_path = options.output_file_path

    prog_intro(path=target_conf_file_path)

    if os.path.exists(target_conf_file_path):
        print
        print _(
            'Target configuration file (%(target_conf_file_path)s)'
            ' already exists.') % vars()
        if console.ask_yesno(_('Remove existing target file'), False):
            print _(
                'Removing last configuration file created with burn-configure'
                '...')
            os.remove(target_conf_file_path)
        else:
            print _(
                'Exiting... Please remove or rename last configuration file: '
                '%(target_conf_file_path)s') % vars()

    # Set up a target config, populated from template.
    target_config = configure.make_config_from_template(
        options.template_file_path)

    configure_sections = target_config.sections()
    section = ''
    #beginning confuguration
    if 'general' in configure_sections:
        section = 'general'
        options = target_config.options(section)
        if 'external_decoding' in options:
            print
            current = console.make_boolean_response(
                target_config.get(section, 'external_decoding'))
            print _('Keep native audio decoding?')
            print _(
                '\tBurn is able to transform compressed audio files'
                ' (MP3, Ogg Vorbis) in WAV.')
            print _('\tChoose \'y\' if you want to keep native decoding. ')
            print _(
                '\tChoose \'n\' if you want to use external decoders'
                ' such as mpg321, ogg123, lame, etc.')
            print _(
                '\t(You will need further editing of burn configuration file)')
            response = console.ask_yesno(
                _("Keep native audio decoding"), current)
            target_config.set(
                section, 'external_decoding',
                console.make_yesno_response(response))
        if 'ask_root' in options:
            print
            current = console.make_boolean_response(
                target_config.get(section, 'ask_root'))
            print _('Prompt user if he is not root?')
            print _('\tBurn can prompt the user if he is not root.')
            print _('\tChoose \'y\' if you want to keep burn prompting you. ')
            print _('\tChoose \'n\' if you don\'t want this question anymore.')
            print _(
                '\t(disable this option if your user has'
                ' permissions to write with cd-writer)')
            response = console.ask_yesno(
                _("Prompt user if he is not root"), current)
            target_config.set(
                section, 'ask_root',
                console.make_yesno_response(response))
    if 'ISO' in configure_sections:
        section = 'ISO'
        options = target_config.options(section)
        if 'tempdir' in options:
            print
            current = target_config.get(section, 'tempdir')
            print _('Which is your temporary directory?')
            while True:
                tmpdr = console.ask_value(
                    _("Temporary directory path"), current)
                if tmpdr == '':
                    break
                if os.path.exists(tmpdr) and os.path.isdir(tmpdr):
                    target_config.set(section, 'tempdir', tmpdr)
                    break
                else:
                    print tmpdr, _('invalid path... skipped.')
                    break
        if 'image' in options:
            print
            current = target_config.get(section, 'image')
            print _('Temporary ISO name?')
            while True:
                image_filename = console.ask_value(
                    _("Temporary ISO image filename"), current)
                if image_filename == '':
                    break
                else:
                    target_config.set(section, 'image', image_filename)
                    break
        if 'windows_read' in options:
            print
            current = console.make_boolean_response(
                target_config.get(section, 'windows_read'))
            print _('Enable Joliet?')
            print _(
                '\tYou should enable this option if you want'
                ' to use your CDs on a Windows system too.')
            response = console.ask_yesno(
                _("Enable Joliet data (for Windows compatibility)"),
                current)
            target_config.set(
                section, 'windows_read',
                console.make_yesno_response(response))
        if 'mount_dir' in options:
            print
            current = target_config.get(section, 'mount_dir')
            print _('Which is your preferred mount point?')
            print _('\tBurn allows you to see image contents.')
            print _('\tWhere do you want to mount the image?')
            while True:
                tmpdr = console.ask_value(
                    _("Mount point directory path"), current)
                if tmpdr == '':
                    break
                if os.path.exists(tmpdr) and os.path.isdir(tmpdr):
                    target_config.set(section, 'mount_dir', tmpdr)
                    break
                else:
                    print tmpdr, _('invalid path... skipped.')
                    break
    if 'CD-writer' in configure_sections:
        section = 'CD-writer'
        options = target_config.options(section)
        if 'device' in options:
            hypothesis_count = 1
            current = target_config.get(section, 'device')
            print _(
                '\nWhich is your cd-dvd writer device?'
                '\n\tEnter either the device file (e.g. /dev/hdc) or '
                'the symbolic link to it (e.g. /dev/cdrom or /dev/cdrw).\n'
                '\tTraditional SCSI descriptions of devicetype:bus/target/lun '
                'specification (e.g. 1,0,0) are accepted too.\n')
            print _('\n\n\tPress a key to start guessing your device.\n')
            console.getch()
            if giveme_realpath('/dev/cdrw'):
                print _(
                    '\n\t* Hypotesis #'
                    ), hypothesis_count, _( ': '), giveme_realpath('/dev/cdrw')
                print _(
                    '\t\t("/dev/cdrw", which usually identifies a '
                    'cd-writer unit, points to this device.)')
                hypothesis_count += 1
            if giveme_realpath('/dev/dvdrw'):
                print _(
                    '\t* Hypotesis #'
                    ),hypothesis_count, _( ': '),giveme_realpath('/dev/dvdrw')
                print _(
                    '\t\t("/dev/dvdrw", which usually identifies a dvd-writer '
                    'unit, points to this device.)')
                hypothesis_count += 1
            if giveme_realpath('/dev/cdrom'):
                print _(
                    '\t* Hypotesis #'
                    ), hypothesis_count, _( ': '),giveme_realpath('/dev/cdrom')
                print _(
                    '\t\t("/dev/cdrom" points to this device. If your '
                    'cd-reader\n\t\t unit is the same of your cd-writer '
                    'unit this should be your device)')
                hypothesis_count += 1
            if giveme_realpath('/dev/dvd'):
                print _(
                    '\t* Hypotesis #'
                    ), hypothesis_count, _( ': '),giveme_realpath('/dev/dvd')
                print _(
                    '\t\t("/dev/dvd" points to this device. If your dvd-reader'
                    '\n\t\t unit is the same of your cd-writer '
                    'unit this should be your device)')
                hypothesis_count += 1
            print '\n\tPress a key to see wodim\'s device list output.\n'
            console.getch()
            print device.device_list_output()
            if console.ask_yesno(_(
                '\tDo you also want to see bus/target/lun scsi '
                'specifications'), False):
                print device.bus_list_output()
            while True:
                print _('\n')
                tmpdr = console.ask_value(
                    _("Optical media recording device"), current)
                if tmpdr == '':
                    break
                else:
                    target_config.set(section, 'device', tmpdr)
                    break
        if 'speed' in options:
            print
            current = target_config.get(section, 'speed')
            print _('At which speed do you want to burn?')
            print _('\tRemember: higher speed may lead to buffer underrun.')
            while True:
                spd = console.ask_value(
                    _("Recording speed"), current)
                if spd == '':
                    break
                else:
                    target_config.set(section, 'speed', spd)
                    break
        if 'driver' in options:
            print
            current = target_config.get(section, 'driver')
            print _('Does your CD-writer use a specific driver?')
            print _('\tPossible values are: ')
            values = [
                "tcdd2600", "plextor", "plextor-scan",
                "generic-mmc", "generic-mmc-raw",
                "ricoh-mp6200", "yamaha-cdr10x", "teac-cdr55",
                "sony-cdu920", "sony-cdu948", "taiyo-yuden", "toshiba",
                ]
            print textwrap.fill(
                ", ".join(values),
                initial_indent="\t\t", subsequent_indent="\t\t",
                break_long_words=False)

            while True:
                drvr = console.ask_value(
                    _("Driver value for media writer device"), current)
                if drvr == '':
                    break
                else:
                    target_config.set(section, 'driver', drvr)
                    break
        if 'burnfree' in options:
            print
            current = console.make_boolean_response(
                target_config.get(section, 'burnfree'))
            print _(
                'Do you want to turn the support for'
                ' Buffer Underrun Free writing on?')
            print _(
                '\tThis only works for drives that support'
                ' Buffer Underrun Free technology')
            response = console.ask_yesno(
                _("Enable support for Buffer Underrun Free"), current)
            target_config.set(
                section, 'burnfree',
                console.make_yesno_response(response))
    if 'CD-reader' in configure_sections:
        section = 'CD-reader'
        print
        if console.ask_yesno(
            _('Do you have a second unit as a CD-reader'), False):
            options = target_config.options(section)
            hypothesis_count = 1
            current = target_config.get(section, 'device')
            print _(
                '\nWhich is your cd-dvd reader device?'
                '\n\tEnter either the device file (e.g. /dev/hdc) or the '
                'symbolic link to it (e.g. /dev/cdrom or /dev/cdrw).\n'
                '\tTraditional SCSI descriptions of '
                'devicetype:bus/target/lun specification (e.g. 1,0,0) '
                'are accepted too.\n'
                '\n\n\tPress a key to start guessing your device.\n')
            console.getch()
            if giveme_realpath('/dev/cdrom'):
                print _('\t* Hypotesis #'), hypothesis_count, _(
                    ': '), giveme_realpath('/dev/cdrom')
                print _(
                    '\t\t("/dev/cdrom" points to this device.')
                hypothesis_count += 1
            if giveme_realpath('/dev/dvd'):
                print _('\t* Hypotesis #'), hypothesis_count, _(
                ': '), giveme_realpath('/dev/dvd')
                print _(
                    '\t\t("/dev/dvd" points to this device.')
                hypothesis_count += 1
            print '\n\tPress a key to see wodim\'s device list output.\n'
            console.getch()
            print device.device_list_output()
            if console.ask_yesno(_(
                '\tDo you also want to see bus/target/lun '
                'scsi specifications'), False):
                print device.bus_list_output()
                while True:
                    tmpdr = console.ask_value(
                        _("Optical media reading device"), current)
                    if tmpdr == '':
                        break
                    else:
                        target_config.set(section, 'device', tmpdr)
                        break
            if 'driver' in options:
                print
                current = target_config.get(section, 'driver')
                print _('Does your CD-reader use a specific driver?')
                print _('\tPossible values are: ')
                values = [
                    "tcdd2600", "plextor", "plextor-scan",
                    "generic-mmc", "generic-mmc-raw",
                    "ricoh-mp6200", "yamaha-cdr10x", "teac-cdr55",
                    "sony-cdu920", "sony-cdu948", "taiyo-yuden", "toshiba",
                    ]
                print textwrap.fill(
                    ", ".join(values),
                    initial_indent="\t\t", subsequent_indent="\t\t",
                    break_long_words=False)
                while True:
                    drvr = console.ask_value(
                        _("Driver value for media writer device"), current)
                    if drvr == '':
                        break
                    else:
    #                   target_config.set(section, 'driver', drvr)
                        break
    if 'Media' in configure_sections:
        section = 'Media'
        options = target_config.options(section)
        if 'size' in options:
            print
            current = target_config.get(section, 'size')
            print _('Which is the most common capacity of your target CDs?')
            while True:
                tmpdr = console.ask_value(
                    _("Media capacity (MB)"), current)
                if tmpdr == '':
                    break
                else:
                    target_config.set(section, 'size', tmpdr)
                    break
        if 'media-check' in options:
            print
            current = console.make_boolean_response(
                target_config.get(section, 'media-check'))
            print _('Do you want burn to auto-check target CD capacity?')
            print _('\tThis function uses cdrdao.')
            response = console.ask_yesno(
                _("Check target media capacity"), current)
            target_config.set(
                section, 'media-check',
                console.make_yesno_response(response))

    configure.write_to_file(target_config, target_conf_file_path)
    print
    print
    print _('Congratulations!')
    print _('Now you have your new configuration file:')
    print target_conf_file_path
    print _('Please rename it and place it as ~/.burnrc or /etc/burn.conf')


if __name__ == '__main__':
    exit_status = main()
    sys.exit(exit_status)


# Local variables:
# mode: python
# coding: utf-8
# End:
# vim: filetype=python fileencoding=utf-8 :
