#! /usr/bin/python3 -sP
# -*- coding: utf-8 -*-
#  Copyright (C) 2009 Stewart Adam
#  Copyright (C) 2007, 2008, 2009 Dennis Gilmore
#  This file is part of rpmfusion-packager.

#  rpmfusion-packager is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.

#  rpmfusion-packager 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 General Public License for more details.

#  You should have received a copy of the GNU General Public License
#  along with rpmfusion-packager.  If not, see <http://www.gnu.org/licenses/>.

#from six.moves import input
import os
import sys
import rpmfusion_cert
import pycurl
import argparse

def download_cert(location, file):
    '''Download the cert and write to file. WARNING: Overwrites files!'''
    fp = open(file, 'wb')
    curl = pycurl.Curl()
    curl.setopt(pycurl.URL, location)
    curl.setopt(pycurl.FOLLOWLOCATION, 1)
    curl.setopt(pycurl.MAXREDIRS, 5)
    curl.setopt(pycurl.CONNECTTIMEOUT, 30)
    curl.setopt(pycurl.TIMEOUT, 300)
    curl.setopt(pycurl.NOSIGNAL, 1)
    curl.setopt(pycurl.WRITEDATA, fp)
#    curl.setopt(pycurl.SSL_VERIFYPEER, False)
    try:
        curl.perform()
    except:
        import traceback
        traceback.print_exc(file=sys.stderr)
        sys.stderr.flush()
    curl.close()
    fp.close()
    print("Saved: %s" % file)

def parse_args():
    parser = argparse.ArgumentParser(description='Usually just run rpmfusion-packager-setup with no options')
    parser.add_argument(
        '-U', '--url', dest='fas_url', metavar='url',
        default='https://admin.rpmfusion.org/accounts/',
        help='FAS URL (Default: https://admin.rpmfusion.org/accounts/)'
    )
    return parser.parse_args()

def main():
    args = parse_args()
    user_home = os.path.expanduser('~')
    user_cert = os.path.join(user_home, '.rpmfusion.cert')
    print('Setting up RPM Fusion packager environment')
    #if not os.path.isfile(os.path.join(user_home, '.rpmfusion.user')):
    #    username = input('Enter your RPM Fusion username: ')
    #    fh = open(os.path.join(user_home, '.rpmfusion.user'), 'w')
    #    fh.write(username)
    #    fh.close()
    #else:
    #    print("~/.rpmfusion.user already exists - skipping")
    if not os.path.isfile(user_cert):
        print("You need a client certificate from the RPM Fusion Account System")
        try:
            rpmfusion_cert.create_user_cert()
        except rpmfusion_cert.rpmfusion_cert_error as e:
            print(e)
            print("You might want to run rpmfusion-cert -n to "
                "regenerate SSL certificate. For more info see "
                "https://rpmfusion.org/Contributors#If_SSL_certificate_expired")
            sys.exit(1)
    else:
        #check if the cert has expired  if it has lets get a new one
        try:
            if rpmfusion_cert.certificate_expired():
                username = rpmfusion_cert.read_user_cert()
                print("Certificate has expired, getting a new one")
                rpmfusion_cert.create_user_cert(username)
            elif rpmfusion_cert.verify_cert():
                username = rpmfusion_cert.read_user_cert()
                print("Certificate expires soon, getting a new one")
                rpmfusion_cert.create_user_cert(username)
        except rpmfusion_cert.rpmfusion_cert_error as e:
            print(e)
            sys.exit(1)

if __name__ == "__main__":
    main()
