#!/usr/bin/env python3
"""LICENSE
Copyright 2017 Hermann Krumrey <hermann@krumreyh.com>

This file is part of ci-scripts.

ci-scripts 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 3 of the License, or
(at your option) any later version.

ci-scripts 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 ci-scripts.  If not, see <http://www.gnu.org/licenses/>.
LICENSE"""

import os
import sys
import argparse
from ci_scripts.common import process_call


def main():
    """
    Deploys a flask application
    :return: None
    """

    parser = argparse.ArgumentParser()
    parser.add_argument("project_home",
                        help="The root directory of the flask application")
    project_home = parser.parse_args().project_home

    if not project_home.endswith("/"):
        project_home += "/"

    if not os.path.isdir(project_home):
        print(project_home + " does not exist")
        sys.exit(1)

    process_call(["python3", "-m", "venv", "flask-app"])
    link_mysql("flask-app")
    process_call(["flask-app/bin/python", "setup.py", "install"])

    process_call(["rsync", "-a", "--delete-after", "flask-app", project_home])
    process_call(["rsync", "-a", "--delete-after", "app.wsgi", project_home])

    if os.path.isfile("generate_secrets.py"):
        process_call(["python", "generate_secrets.py"])

    if os.path.isfile("secrets.json"):
        process_call([
            "rsync", "-a", "--delete-after", "secrets.json", project_home
        ])
        os.remove("secrets.json")


def link_mysql(venv_path: str):
    """
    Links mysql libraries to a venv
    :param venv_path: The venv to which to link the libs to
    :return: None
    """
    if os.path.isdir("/usr/lib/python3/dist-packages/"):

        # Find _mysql.so
        _mysql = ""
        for lib in os.listdir("/usr/lib/python3/dist-packages"):
            if lib.startswith("_mysql.") and lib.endswith(".so"):
                _mysql = lib
                break

        # Find site_packages
        site_packages = os.path.join(venv_path, "lib")
        python_version = os.listdir(site_packages)[0]
        site_packages = \
            os.path.join(site_packages, python_version, "site-packages")

        # Link libs
        for lib in [_mysql, "MySQLdb", "_mysql_exceptions.py"]:
            source = os.path.join(site_packages, lib)
            dest = os.path.join(venv_path, "lib/site_packages", lib)
            if os.path.exists(source):
                process_call(["ln", "-s", source, dest])


if __name__ == "__main__":
    main()
