#! /bin/bash
#
# Copyright Qualcomm Technologies Inc, 2019.
# All Rights Reserved
#
# This script sets up a Python 3.5 virtual environment on a target
# machine and then installs the Python wheels for the application into
# it.
#
# This script does the following:
#
# a) A Python 3.5 virtualenv is created in the folder
#    /usr/share/pyconfigtool, which is where the debian package has
#    been instructed to put the wheels that are in the deb package.
#
# b) We then upgrade pip, setuptools and wheel in that virtualenv to
#    be the latest.
#
# c) The application wheel and all the plugin wheels are then
#    installed into this virtualenv. These will include multiple
#    third-party Python packages which are fetched from the global
#    Python Index (pypi.python.org).
#
# This script issues information to stdout which indicates the
# progress of the work being done by the script. This information is
# used by the logwindow script to provide a user-friendly progress
# bar.
set -e
echo -------------------------------------------------
echo Setting up the Qualcomm Device Configuration Tool
echo -------------------------------------------------
echo

echo This might take some time...

export PROG_MAX=18
export PYVER=3.5
export PYNUM=35
export VENV=pyenv$PYNUM
export INSTALL_DIR=/usr/share/pyconfigtool
export BIN_DIR=/usr/local/bin
let "CURR_PROG=0" || true

function emit_progress {
    let "CURR_PROG++" || true
    echo PROGRESSBAR: $CURR_PROG/$PROG_MAX
}

# Test that Python is installed
if [ -x /usr/bin/python$PYVER ] ; then
    echo Using Python$PYVER
    export PYTHON_LOCATION=/usr/bin/python$PYVER
else
    echo Please install Python $PYVER package
    exit 1
fi
emit_progress

echo Building a virtualenv...
$PYTHON_LOCATION -m venv $VENV
emit_progress

# Install/upgrade wheel, setuptools and pip to ensure we can install
$VENV/bin/python -m pip install -U wheel setuptools pip
emit_progress

# Install public packages that we have to redistribute
echo Installing public wheels
for WHEEL in `ls wheels/public/*.whl`
do
    echo Installing wheel $WHEEL
    $VENV/bin/pip install $WHEEL
    emit_progress
done

# Now install the application wheel into this virtualenv
echo Installing wheels
for WHEEL in `ls wheels/*.whl`
do
    echo Installing application wheel $WHEEL
    $VENV/bin/pip install $WHEEL
    emit_progress
done

# Install all the plugin wheels
for WHEEL in `ls wheels/plugins/*.whl`
do
    echo Installing plugin wheel $WHEEL
    $VENV/bin/pip install $WHEEL
    emit_progress
done

echo Creating application links
if [ ! -d $BIN_DIR ] ; then
    mkdir -f $BIN_DIR
    chmod 755 $BIN_DIR
fi
ln -sf $INSTALL_DIR/$VENV/bin/qconf $BIN_DIR/qconf
ln -sf $INSTALL_DIR/$VENV/bin/pyconfigcmd $BIN_DIR/pyconfigcmd
emit_progress

echo Successfully installed the application and plugin wheels.
