#!/usr/bin/python2

# Copyright 2014-2015  Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2, or (at your option) any later
# version.  This program is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY expressed or implied, including the
# implied warranties 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.
#
# Any Red Hat trademarks that are incorporated in the source
# code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission
# of Red Hat, Inc.
#
# Author: Kushal Das <kdas@redhat.com>


import os
import sys
import argparse

VERSION = '0.2'

def convert_to_server():
    """This function tries to run a series of yum commands
to convert a Fedora cloud instance into a Fedora server instance.
    """
    cmd = "dnf -y remove fedora-release-cloud"
    ret_code = os.system(cmd)
    if ret_code != 0:
        print "There was issues while converting to Fedora Server. Please report the error"
        print "Use https://paste.fedoraproject.org for pasting the output from this command."
        return

    # Now we now that fedora-release server is in the system
    # We will try to pull down the rest of the packages. 
    cmd = 'dnf groupinstall "Fedora Server" -y'
    ret_code = os.system(cmd)
    if ret_code != 0:
        print "Error while installing packages. Please check the network."
        return


def main():
    """
    Main function of the script.
    """
    parser = argparse.ArgumentParser()
    parser.add_argument("-d", "--disable-cloud-service", help="Disable cloud-init service",
                        action="store_true")
    parser.add_argument("-v", "--version", help="Prints the version of the tool",
                        action="store_true")
    args = parser.parse_args()

    if args.version:
        print 'cloudtoserver version %s' % VERSION
        return
    # First let us give some warning to the user.
    print "This will try to convert your Fedora cloud instance to a Fedora Server instance."
    while True:
        inp = raw_input("Continue? y/N: ")
        inp = inp.strip()
        if inp == 'N':
            return
        if inp.upper() == 'Y':
            break
    # Now the normal flow of the application
    convert_to_server()
    if args.disable_cloud_service:
        print "Disabling cloud-init service. This won't run anymore by default."
        cmd = "systemctl disable cloud-init.service"
        os.system(cmd)


if __name__ == '__main__':
    main()
