#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
##########################################################################
# Maj-Auto - Manage automatique update of EOLE server
# Copyright © 2015 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
##########################################################################

import argparse
from os import system
from sys import exit
import re
from pyeole.i18n import i18n
from pyeole.ansiprint import print_red
from creole.eoleversion import EOLE_RELEASE, LAST_RELEASE, EOLE_VERSION

_ = i18n('creole')

def parse_cmdline():
    """Parse commande line.
    """
    description = _(u"This script will upgrade to a new release of this distribution")
    parser = argparse.ArgumentParser(prog='Maj-Release',
                                     description=description,
                                     add_help=False)

    parser.add_argument('-h', '--help',
                        action='help',
                        help=_(u"show this help message and exit"))

    parser.add_argument('--release', help=_(u"Target release number"))

    parser.add_argument('-f', '--force', action='store_true',
                        help=_(u"Do not ask confirmation"))

    opts = parser.parse_args()

    return opts


def main():
    opts = parse_cmdline()

    print(_(u"This script will upgrade to a new release of this distribution"))
    all_releases = []
    current_release = int(EOLE_RELEASE.split('.')[-1])
    choices = list(range(current_release+1, int(LAST_RELEASE)+1))
    # Last is firt displayed
    if choices == []:
        print("")
        print_red(_(u"No stable new release available"))
        print("")
        exit(1)
    choices.reverse()
    for release_suffix in choices:
        all_releases.append(EOLE_VERSION + '.' + str(release_suffix))

    while True:
        if opts.release is not None:
            choice = opts.release
        else:
            for idx, release in enumerate(all_releases):
                print("{0}: {1}".format(idx+1, release))
            print(_(u"q|quit: abort"))

            try:
                choice = input("[1] : ")
            except (KeyboardInterrupt, EOFError):
                print_red(_("\nUpgrade aborted by user"))
                exit(0)

        if choice == '':
            # User hit enter
            choice = 1
        elif choice in all_releases:
            # User entrer release number
            choice = all_releases.index(choice) + 1
        else:
            try:
                choice = int(choice)
            except ValueError:
                if re.match(r'^q(uit)?', choice):
                    print_red(_(u"Voluntary stay of proceedings"))
                    exit(0)
                else:
                    print_red(_(u"Invalid response: {0}").format(choice))
                    if opts.release is not None:
                        exit(1)
                    else:
                        continue

        if not 1 <= choice <= len(choices):
            print_red(_(u"Invalid response: {0}").format(choice))
            if opts.release is not None:
                exit(1)
            else:
                continue
        else:
            break

    release = all_releases[choice - 1]
    if opts.force:
        force = '--force-update'
    else:
        force = ''

    # variable pour faciliter l'intégration des versions de dev via eole-ci-tests
    option = ''

    majrel = system('/usr/bin/Maj-Auto --release {0} {1} {2}'.format(release, force, option))

    exit(majrel)

if __name__ == '__main__':
    main()
