#!/usr/bin/env python
#################################################################################
#  Licensed to the Apache Software Foundation (ASF) under one
#  or more contributor license agreements.  See the NOTICE file
#  distributed with this work for additional information
#  regarding copyright ownership.  The ASF licenses this file
#  to you 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.
################################################################################
"""
This script is a python implementation of the "boot.go" script in "beam-sdks-python-container"
project of Apache Beam, see in:

https://github.com/apache/beam/blob/release-2.14.0/sdks/python/container/boot.go

It is implemented in golang and will introduce unnecessary dependencies if used in pure python
project. So we add a python implementation which will be used when the python worker runs in
process mode. It downloads and installs users' python artifacts, then launches the python SDK
harness of Apache Beam.
"""
import argparse
import hashlib
import os
from subprocess import call

import grpc
import logging
import sys

from apache_beam.portability.api.beam_provision_api_pb2_grpc import ProvisionServiceStub
from apache_beam.portability.api.beam_provision_api_pb2 import GetProvisionInfoRequest
from apache_beam.portability.api.beam_artifact_api_pb2_grpc import ArtifactRetrievalServiceStub
from apache_beam.portability.api.beam_artifact_api_pb2 import (GetManifestRequest,
                                                               GetArtifactRequest)
from apache_beam.portability.api.endpoints_pb2 import ApiServiceDescriptor

from distutils.dist import Distribution

from google.protobuf import json_format, text_format

from pkg_resources import get_distribution, parse_version


def check_not_empty(check_str, error_message):
    if check_str == "":
        logging.fatal(error_message)
        exit(1)


python_exec = sys.executable

PYTHON_REQUIREMENTS_FILE = "_PYTHON_REQUIREMENTS_FILE"
PYTHON_REQUIREMENTS_CACHE = "_PYTHON_REQUIREMENTS_CACHE"
PYTHON_REQUIREMENTS_INSTALL_DIR = "_PYTHON_REQUIREMENTS_INSTALL_DIR"


def append_path_to_env(env, name, value):
    if name in env:
        env[name] = os.pathsep.join([value, env[name]])
    else:
        env[name] = value


def get_site_packages_paths(prefix):
    install_obj = Distribution().get_command_obj('install', create=True)
    install_obj.prefix = prefix
    install_obj.finalize_options()
    installed_dir = [install_obj.install_purelib]
    if install_obj.install_purelib != install_obj.install_platlib:
        installed_dir.append(install_obj.install_platlib)
    return installed_dir


def get_prefix_option(requirements_install_path):
    pip_version = get_distribution("pip").version
    # since '--prefix' option is only supported for pip 8.0+, so here we fallback to
    # use '--install-option' when the pip version is lower than 8.0.0.
    if parse_version(pip_version) >= parse_version('8.0.0'):
        return ["--prefix", requirements_install_path]
    else:
        return ['--install-option', '--prefix=' + requirements_install_path]


def pip_install_requirements():
    if (PYTHON_REQUIREMENTS_FILE in os.environ
            and PYTHON_REQUIREMENTS_INSTALL_DIR in os.environ):
        requirements_file_path = os.environ[PYTHON_REQUIREMENTS_FILE]
        requirements_install_path = os.environ[PYTHON_REQUIREMENTS_INSTALL_DIR]
        if PYTHON_REQUIREMENTS_CACHE in os.environ:
            requirements_cache_path = os.environ[PYTHON_REQUIREMENTS_CACHE]
        else:
            requirements_cache_path = None

        env = dict(os.environ)
        installed_python_path = os.pathsep.join(get_site_packages_paths(requirements_install_path))
        installed_python_script_path = os.path.join(requirements_install_path, "bin")
        append_path_to_env(env, "PYTHONPATH", installed_python_path)
        append_path_to_env(env, "PATH", installed_python_script_path)

        pip_install_commands = [python_exec, "-m", "pip", "install", "--ignore-installed", "-r",
                                requirements_file_path]
        pip_install_commands.extend(get_prefix_option(requirements_install_path))
        if requirements_cache_path is not None:
            pip_install_commands.extend(["--find-links", requirements_cache_path])

        logging.info("Run command: %s\n" % " ".join(pip_install_commands))
        exit_code = call(
            pip_install_commands, stdout=sys.stdout, stderr=sys.stderr, env=env)
        if exit_code > 0:
            raise Exception(
                "Run command: %s error! exit code: %d" %
                (" ".join(pip_install_commands), exit_code))

        os.environ["PYTHONPATH"] = env["PYTHONPATH"]
        os.environ["PATH"] = env["PATH"]


if __name__ == "__main__":
    # print INFO and higher level messages
    logging.basicConfig(stream=sys.stdout, level=logging.INFO)

    parser = argparse.ArgumentParser()

    parser.add_argument("--id", default="", help="Local identifier (required).")
    parser.add_argument("--logging_endpoint", default="",
                        help="Logging endpoint (required).")
    parser.add_argument("--artifact_endpoint", default="",
                        help="Artifact endpoint (required).")
    parser.add_argument("--provision_endpoint", default="",
                        help="Provision endpoint (required).")
    parser.add_argument("--control_endpoint", default="",
                        help="Control endpoint (required).")
    parser.add_argument("--semi_persist_dir", default="/tmp",
                        help="Local semi-persistent directory (optional).")

    args = parser.parse_args()

    worker_id = args.id
    logging_endpoint = args.logging_endpoint
    artifact_endpoint = args.artifact_endpoint
    provision_endpoint = args.provision_endpoint
    control_endpoint = args.control_endpoint
    semi_persist_dir = args.semi_persist_dir

    check_not_empty(worker_id, "No id provided.")