// Copyright (c) 2017 VMware, Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#!/usr/bin/python

"""
The script is to export the existing projects of Harbor into a file.
It's only for VIC 1.2 migration.
"""

import json
import fileinput
from optparse import OptionParser
import os
import MySQLdb
import sys

class Parameters(object):
    def __init__(self):
        self.dbuser = ''
        self.dbpwd = ''
        self.exportpath = ''
        self.init_from_input()

    @staticmethod
    def parse_input():
        usage = "usage: %prog [options] <dbuser> <dbpwd> <exportpath>"
        parser = OptionParser(usage)
        parser.add_option("-u", "--dbuser", dest="dbuser", help="db user")
        parser.add_option("-p", "--dbpwd", dest="dbpwd", help="db password")
        parser.add_option("-o", "--exportpath", dest="exportpath", help="the path of exported json file")

        (options, args) = parser.parse_args()
        return (options.dbuser, options.dbpwd, options.exportpath)

    def init_from_input(self):
        (self.dbuser, self.dbpwd, self.exportpath) = Parameters.parse_input()

class Project:
    def __init__(self, project_id, name, public):
        self.project_id = project_id
        self.project_name = name
        if public == 0:
            self.public = "false"
        elif public == 1:
            self.public = "true"
        else:
            self.public = "false"

class HarborUtil:
    def __init__(self, dbuser, dbpwd):
        self.serverName = 'localhost'
        self.user = dbuser
        self.password = dbpwd
        self.port = '3306'
        self.subDB = 'registry'
        self.db = None
        self.cursor = None

    def connect(self):
        try:
            self.db = MySQLdb.connect(host=self.serverName, user=self.user,
                                      passwd=self.password, db=self.subDB)
            self.cursor = self.db.cursor()
        except Exception, e:
            raise Exception(e)

    def close(self):
        try:
            self.cursor.close()
            self.db.close()
        except Exception, e:
            print str(e)

    def get_projects(self):
        projects = []
        try:
            query = "SELECT project_id, name, public from registry.project where deleted=0"
            self.cursor.execute(query)
            self.cursor.fetchall()
            for result in self.cursor:
                projects.append(Project(int(result[0]), result[1], result[2]))
            return projects
        except Exception, e:
            raise Exception(e)

def delfile(src):
    if not os.path.exists(src):
        return
    try:
        os.remove(src)
    except Exception, e:
        raise Exception("unable to delete file: %s, error: %s" % (src, str(e)))

def main():
    commandline_input = Parameters()
    harbor = HarborUtil(commandline_input.dbuser, commandline_input.dbpwd)

    try:
        harbor.connect()
        projects = harbor.get_projects()
        if len(projects) == 0:
            return

        harbor_projects_json = commandline_input.exportpath + '/harbor_projects.json'
        delfile(harbor_projects_json)

        with open(harbor_projects_json, 'w') as outfile:
            json.dump({'projects': [project.__dict__ for project in projects]}, outfile, sort_keys=True, indent=4)

    except Exception, e:
        print e
        sys.exit(1)
    finally:
        harbor.close()

if __name__ == '__main__':
    main()