#!/usr/bin/python3
# -*- mode: python; coding: utf-8 -*-
#
##########################################################################
# pyeole.iso - manage EOLE ISO images
# Copyright © 2018 Pôle de compétences EOLE <eole@ac-dijon.fr>
#
# License CeCILL:
#  * in french: http://www.cecill.info/licences/Licence_CeCILL_V2-fr.html
#  * in english http://www.cecill.info/licences/Licence_CeCILL_V2-en.html
##########################################################################

"""Manipulate EOLE ISO images

SYNOPSYS
========

    eole-iso --release 2.7.0 list-point-releases
    eole-iso --release 2.7.0 get-last-point-release
    eole-iso --verbose --release 2.7.0 download

"""

from __future__ import absolute_import, print_function, unicode_literals

import sys
import argparse

from pyeole.i18n import i18n
from pyeole.log import init_logging
from pyeole import scriptargs

from pyeole.iso import IsoEOLE

_ = i18n('eole-iso')

log = None


def get_iso_name(iso, options):
    """Get the ISO image name

    """
    print(iso.name)


def get_iso_url(iso, options):
    """Get the ISO image URL

    """
    print(iso.iso_url)


def list_point_releases(iso, options):
    """List all the point releases

    """
    print('\n'.join(iso.point_releases))


def get_last_point_release(iso, options):
    """Get the latest point releases

    """
    print(iso.last_point_release)


def download(iso, options):
    """Download the ISO image

    """
    iso.download(path=options.path, silent=not options.verbose, limit_rate=options.limit_rate)


def verify(iso, options):
    """Verify the SHA256 checksum of the ISO image

    """
    iso.verify(silent=not options.verbose)


def parse_args():
    parser = argparse.ArgumentParser(description=_("Manipulate EOLE ISO images"),
                                     parents=[scriptargs.logging()])

    parser.add_argument('-r', '--release', required=True,
                        type=str, help=_("EOLE release"))

    parser.add_argument('-p', '--proxy', type=str, help=_("HTTP proxy"))

    actions = parser.add_subparsers(help=_('actions for EOLE ISO'))


    name_action = actions.add_parser('get-iso-name',
                                     help=_('get EOLE ISO image name'))
    name_action.set_defaults(func=get_iso_name)


    url_action = actions.add_parser('get-iso-url',
                                    help=_('get EOLE ISO image URL'))
    url_action.set_defaults(func=get_iso_url)


    list_action = actions.add_parser('list-point-releases',
                                     help=_('list all point releases'))
    list_action.set_defaults(func=list_point_releases)


    get_action = actions.add_parser('get-last-point-release',
                                    help=_('get the latest point release'))
    get_action.set_defaults(func=get_last_point_release)


    download_action = actions.add_parser('download',
                                         help=_('download and verify latest point release of EOLE ISO'))

    download_action.add_argument('-l', '--limit-rate', type=str, default='0',
                                 help=_('limit the download bandwith (ex: 20k)'))

    download_action.add_argument('-p', '--path', type=str,
                                 help=_('copy from this source path'))

    download_action.set_defaults(func=download)


    verify_action = actions.add_parser('verify',
                                       help=_('verify the checksum of a downloaded ISO'))

    verify_action.set_defaults(func=verify)

    options = parser.parse_args()

    if options.verbose:
        options.log_level = 'info'

    if options.debug:
        options.log_level = 'debug'

    return options


def main():
    options = parse_args()

    global log
    log = init_logging(name='eole-iso', as_root=True, level=options.log_level)

    try:
        iso = IsoEOLE(release=options.release, http_proxy=options.proxy)
        options.func(iso, options)
    except KeyboardInterrupt:
        log.error(_("Aborted by user"))
    except Exception as error:
        if options.debug:
            log.debug(error, exc_info=True)
        else:
            log.error(error)

        sys.exit(1)

if __name__ == "__main__":
    main()
