#!/usr/bin/env python2
# -*- coding: utf-8 -*-
#
#    LinOTP - the open source solution for two factor authentication
#    Copyright (C) 2010 - 2019 KeyIdentity GmbH
#
#    This file is part of LinOTP server.
#
#    This program is free software: you can redistribute it and/or
#    modify it under the terms of the GNU Affero General Public
#    License, version 3, as published by the Free Software Foundation.
#
#    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 Affero General Public License for more details.
#
#    You should have received a copy of the
#               GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#
#    E-mail: linotp@keyidentity.com
#    Contact: www.linotp.org
#    Support: www.keyidentity.com
#


import pip
from subprocess import call
import getopt, sys


def usage():
    print """
linotp-pip-update

    -f, --force    force the update
    -h, --help     show this help
    """

def update():
    for dist in pip.get_installed_distributions():
        call("pip install --upgrade " + dist.project_name, shell=True)


def main():
    force = False

    try:
        opts, args = getopt.getopt(sys.argv[1:], "hf", ["help", "force"])
    except getopt.GetoptError as e:
        print str(e)
        sys.exit(1)

    for o, a in opts:
        if o in ("-f", "--force"):
            force = True
        if o in ("-h", "--help"):
            usage()
            sys.exit(2)

    if force:
        update()
    else:
        answer = False
        while not answer:
            res = raw_input("Do you really want to update your python environment? (y/N)")
            answer = res.lower() in ['y', 'n', '']

        if res.lower() == 'y':
            update()
        else:
            print "You canceled the update process."


if __name__ == "__main__":
    main()
