#!/bin/sh
''''[ ! -z $VIRTUAL_ENV ] && exec python -u -- "$0" ${1+"$@"}; command -v python3 > /dev/null && exec python3 -u -- "$0" ${1+"$@"}; exec python2 -u -- "$0" ${1+"$@"} # '''

import sys
import os
import argparse
import shutil
import tempfile
import traceback

HERE = os.path.dirname(__file__)
READIES = os.path.abspath(os.path.join(HERE, ".."))
sys.path.insert(0, READIES)
import paella  # noqa: F401

os.environ["PYTHONWARNINGS"] = 'ignore:DEPRECATION::pip._internal.cli.base_command'

#----------------------------------------------------------------------------------------------

class RMPyToolsSetup(paella.Setup):
    def __init__(self, args):
        paella.Setup.__init__(self, nop=args.nop)
        self.pyver = sys.version_info
        if args.no_reinstall:
            self.reinstall = False
        else:
            self.reinstall = args.reinstall
        self.modern = args.modern
        self.rltest_version = args.rltest_version
        self.ramp_version = args.ramp_version

    def build_and_install_psutil(self, deps):
        self.run("%s/bin/getgcc" % READIES)
        self.install(deps)
        self.pip_install("psutil")

    def common_first(self):
        self.psutil_installed = self.pip_install("psutil", _try=True, output=False) == 0

    def debian_compat(self):
        if not self.psutil_installed:
            self.run("apt-get remove -y python%s-psutil" % ("" if self.pyver[0] == 2 else self.pyver[0]),
                     _try=True, output=False, sudo=True)
            if self.osnick == 'xenial' and self.pyver[0:2] == (3, 6):
                self.build_and_install_psutil("python3.6-dev")
            else:
                self.build_and_install_psutil("python%s-dev" % self.pyver[0])

    def redhat_compat(self):
        if not self.psutil_installed:
            self.build_and_install_psutil("python%s-devel" % self.pyver[0])

    def archlinux(self):
        if not self.psutil_installed:
            self.build_and_install_psutil("python%s-dev" % self.pyver[0])

    def fedora(self):
        if not self.psutil_installed:
            self.run("dnf remove -y python%s-psutil" % self.pyver[0], _try=True, output=False, sudo=True)
            self.build_and_install_psutil("python%s-devel" % self.pyver[0])

    def macos(self):
        self.pip_install("psutil==5.8.0")

    def alpine(self):
        self.install("linux-headers")

    def common_last(self):
        self.install("git")
        if self.reinstall:
            self.pip_uninstall("redis redis-py-cluster ramp-packer RLTest")
            
        # redis-py and redis-py-cluster
        if self.modern:
            # self.pip_install("--no-cache-dir --ignore-installed git+https://github.com/redis/redis-py.git@master")
            pass # will be installed by other packages
        else:
            self.pip_install("--no-cache-dir --ignore-installed git+https://github.com/redisfab/redis-py.git@3.5")

            # redis-py-cluster should be installed from git due to redis-py dependency
            # self.pip_install("--no-cache-dir git+https://github.com/Grokzen/redis-py-cluster.git@master")
            # self.pip_install("--no-cache-dir --ignore-installed redis-py-cluster")
            self.pip_install("--no-cache-dir --ignore-installed git+https://github.com/redisfab/redis-py-cluster@2.1")

        if self.rltest_version is None:
            if self.modern:
                self.rltest_version = 'master'
                self.ramp_version = "master"
            else:
                self.rltest_version = '0.4'
                self.ramp_version = '2.2'

        if self.rltest_version is not None:
            self.pip_install("--no-cache-dir --ignore-installed git+https://github.com/RedisLabsModules/RLTest.git@{VER}".format(VER=self.rltest_version))

        if self.ramp_version is not None:
            self.pip_install("--no-cache-dir --ignore-installed git+https://github.com/RedisLabs/RAMP@{VER}".format(VER=self.ramp_version))

#----------------------------------------------------------------------------------------------

class RMPyToolsUninstall(paella.Setup):
    def __init__(self, args):
        paella.Setup.__init__(self, nop=args.nop)
        self.pip_uninstall("redis redis-py-cluster ramp-packer RLTest")

#----------------------------------------------------------------------------------------------

parser = argparse.ArgumentParser(description='Install RedisLabs Modules Python tools')
parser.add_argument('-n', '--nop', action="store_true", help='no operation')
parser.add_argument('-v', '--verbose', action="store_true", help='Display installed versions')
parser.add_argument('--no-reinstall', action="store_true", default=False, help='Not not reinstall everything')
parser.add_argument('--reinstall', action="store_true", default=False, help='Reinstall everything')
parser.add_argument('--remove', action="store_true", default=False, help='Uninstall everything')
parser.add_argument('--modern', action="store_true", default=False, help='Install modern versions of redis-py (4.x), RLTest, and RAMP')
parser.add_argument('--rltest-version', type=str, default=None, help="RLTest github version/branch")
parser.add_argument('--ramp-version', type=str, default=None, help="RAMP github version/branch")
args = parser.parse_args()

try:
    if args.modern and sys.version_info < (3, 6):
        fatal("Cannot use redis-py 4.0 with Python 2")
    if args.remove:
        RMPyToolsUninstall(args).setup()
    else:
        RMPyToolsSetup(args).setup()
    if args.verbose:
        os.system("{PYTHON} -m pip list | grep -e 'redis\|redis-py\|rltest\|ramp'".format(PYTHON=sys.executable))
except Exception as x:
    traceback.print_exc()
    fatal(str(x))

exit(0)
