#!/usr/bin/env bash
#
# deploy_dm.sh | Complementary script to configure_dm.sh
#
# This script is to be run on the drive module tester PC and finishes the deployment steps.
# In particular:
#
# 1. Extracts the partial driving repo into the privileged user's home directory: zoox/driving
# 2. Creates a Python virtualenv for the drive module test scripts: VirtualEnvs/dm_tester
# 3. Extracts and installs all packages into the virtualenv
# 4. Installs requirements via requirements.txt into the virtualenv
# 5. Patches llama and llama_runner to hide dm_tester directory path and simplify runner CLI
#
# @copyright Highly Confidential and Proprietary Zoox Information. Copyright (c) Zoox
#
# Author: trawat
# Date Created: April 28, 2020
#
debug=""
all="$1" #  optional 1st arg to deploy both env and test scripts when specified

# Common variables for use in this script
dropzone_path="/home/$USER/dropzone"
driving_zip=test_directories.zip
virtualenvs_dir="/home/$USER/VirtualEnvs"
virtualenv_name=dm_venv
zoox_root="/home/$USER/${debug}zoox"
hwtf_tests_dir="${zoox_root}/driving/firmware/validation/dm_tester"
venv_full_path=${virtualenvs_dir}/${virtualenv_name}


# If the dropzone folder doesn't exist then the files we need cannot be found
if [ ! -d "$dropzone_path" ]; then
    echo "Cannot find deployment files. Please ask a Zoox employee to run ./configure_dm.sh"
    echo "on their own system"
    exit 1
fi

# Make sure all destination paths exist
mkdir -p ${zoox_root}
mkdir -p ${virtualenvs_dir}

# remove old driving folder altogether
rm -rf "${zoox_root}/driving" 2> /dev/null
# Move driving files to zoox (unzip to destination)
unzip -o ${dropzone_path}/${driving_zip} -d ${zoox_root}

if [ -n "$all" ]; then
    # Create the virtualenv to be used for keeping the test dependencies
    virtualenv -p python3.6 ${virtualenvs_dir}/${virtualenv_name}

    # Remove *.tar.gz files before unzip
    rm -f ${virtualenvs_dir}/${virtualenv_name}/pkg/* 2> /dev/null

    # Move python packages to venv (unzip to destination)
    unzip -o ${dropzone_path}/py_packages.zip -d ${virtualenvs_dir}/${virtualenv_name}

    # Activate virtualenv and install packages and requirements
    source ${venv_full_path}/bin/activate

    # Install the latest version of the external packages in the pkg directory
    libs=("aenum" \
          "astroid" \
          "attrs" \
          "bitstruct" \
          "cantools" \
          "certifi" \
          "chardet" \
          "diskcache" \
          "filelock"
          "idna" \
          "importlib-metadata" \
          "isort" \
          "lazy-object-proxy" \
          "mccabe" \
          "more-itertools" \
          "mypy-extensions" \
          "packaging" \
          "pluggy" \
          "py" \
          "pybind11" \
          "pylint" \
          "pyparsing" \
          "pytest" \
          "pytest-json-report==1.1.0" \
          "pytest-metadata"
          "pyusb" \
          "requests" \
          "six" \
          "textparser" \
          "toml" \
          "typed-ast" \
          "urllib3" \
          "wcwidth" \
          "wrapt" \
          "zipp"\
          "setuptools" \
          "wheel"
        )
    for public_pkg in ${libs[@]}; do
        pip install $public_pkg --index-url https://pypi.python.org/simple
    done
    # Install all Zoox internal packages
    zoox_packages=("zrpath" "testrail_lib" "llama" "chaski" "canassist")
    for package in $(ls ${venv_full_path}/pkg); do
        internal_package=false
        package_name=${package%%-*}
        for zoox_name in ${zoox_packages[@]}; do
            if [ "$package_name" == "$zoox_name" ]; then
                internal_package=true
            fi
        done
        if [ $internal_package = true ]; then
            pip install ${venv_full_path}/pkg/${package} --no-index
        else
            pip install ${venv_full_path}/pkg/${package} --index-url https://pypi.python.org/simple
        fi
    done

    deactivate
fi

if [ -n "$all" ]; then # skip patching llama_runner.py if deploying scripts only to avoid over-patching
    # Patch llama/llama_runner.py in ${virtualenvs_dir}/${virtualenv_name}/lib/python3.6/site-packages
    echo "Patching llama"
    llama_runner="${venv_full_path}/lib/python3.6/site-packages/llama/llama_runner.py"
    sed -i 's/help="Pytest script directory", required=True/help="Pytest script directory", required=False/g' $llama_runner
    sed -i "s+args.directory+'${hwtf_tests_dir}'+g" $llama_runner
    sed -i "s/import llama_config/import llama_config\\n    print(\"Executing {}\".format(template_name))/g" $llama_runner
    # Update interpeter used in llama runner
    cat $llama_runner > temp.py
    echo "Injecting paths for supporting driving/firmware resources"
    echo "#!${venv_full_path}/bin/python" > $llama_runner
    echo "import sys" >> $llama_runner
    path_to_inject=$(dirname ${hwtf_tests_dir})
    for iteration in 1, 2, 3; do
        echo "sys.path.append(\"${path_to_inject}\")" >> $llama_runner
        path_to_inject=$(dirname ${path_to_inject})
    done
    cat temp.py >> $llama_runner
    rm -f temp.py
    chmod a+x $llama_runner 2> /dev/null
fi

# Patch the hil_class/base_hil.py file to change
# firmware/validation/hil_class/deploy_config.json to
# /home/svc-teststation/zoox/driving/firmware/validation/hil_class/deploy_config.json
base_hil="${zoox_root}/driving/firmware/validation/hil_class/base_hil.py"
sed -i "s+firmware/validation/hil_class/deploy_config.json+${zoox_root}/driving/firmware/validation/hil_class/deploy_config.json+g" $base_hil

# Patch the dm_tester/conftest.py file to change
# firmware/validation/dm_tester/dbc_0521 to
# /home/svc-teststation/zoox/driving/firmware/validation/dm_tester/dbc_0521
conftest="${zoox_root}/driving/firmware/validation/dm_tester/conftest.py"
sed -i "s+firmware/validation/dm_tester/dbc_0521+${zoox_root}/driving/firmware/validation/dm_tester/dbc_0521+g" $conftest

echo "Environment configuration complete"
