#!/usr/bin/python
#
# Copyright (C) 2011, Stefano Rivera <stefanor@ubuntu.com>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
#
# Wraps sensisible-editor in checks for remaining boilerplate.
# Configured through environment variables:
# UDT_EDIT_WRAPPER_EDITOR: The user's usual $EDITOR
# UDT_EDIT_WRAPPER_VISUAL: The user's usual $VISUAL
# UDT_EDIT_WRAPPER_TEMPLATE_RE: An extra boilerplate-detecting regex.
# UDT_EDIT_WRAPPER_FILE_DESCRIPTION: The type of file being edited.

import optparse
import os
import re

from ubuntutools.question import EditFile


def main():
    parser = optparse.OptionParser('%prog [options] filename')
    options, args = parser.parse_args()

    if len(args) != 1:
        parser.error('A filename must be specified')
    body = args[0]
    if not os.path.isfile(body):
        parser.error('File %s does not exist' % body)

    if 'UDT_EDIT_WRAPPER_EDITOR' in os.environ:
        os.environ['EDITOR'] = os.environ['UDT_EDIT_WRAPPER_EDITOR']
    else:
        del os.environ['EDITOR']

    if 'UDT_EDIT_WRAPPER_VISUAL' in os.environ:
        os.environ['VISUAL'] = os.environ['UDT_EDIT_WRAPPER_VISUAL']
    else:
        del os.environ['VISUAL']

    placeholders = []
    if 'UDT_EDIT_WRAPPER_TEMPLATE_RE' in os.environ:
        placeholders.append(re.compile(
            os.environ['UDT_EDIT_WRAPPER_TEMPLATE_RE']))

    description = os.environ.get('UDT_EDIT_WRAPPER_FILE_DESCRIPTION', 'file')

    EditFile(body, description, placeholders).edit()

if __name__ == '__main__':
    main()