#!/bin/bash
#
# pypi_uploader.sh
# Runs as a cron job on sun-tmvm-fwvalapp03-prod and inspects the develop/firmware branch
# within the driving repo for changes to FWVAL python packages.
#
# If changes are found, those packages are built and uploaded into Zoox pypi
#
# @copyright Highly Confidential and Proprietary Zoox Information. Copyright (c) Zoox
#
# Author: trawat
# Date Created: May 12, 2020
#

# Variable declarations, not strictly necessary but defines commonly used variables in one place
abort=1
bot_name="pypi-bot"
cache_file="packages.cache"
channel="#fw-pypi-info"
icon_emoji=":easy:"
monitored_branch="develop/firmware"
temp_file="packages.new"
virtualenv_name="pypi_venv"
zoox_pypi="https://pypi.zooxlabs.com/simple"

# Need this to write files to the proper directory later
run_dir=`pwd`

# Change directory at least two levels up (at least the firmware directory)
cd $(pwd | xargs dirname | xargs dirname)

# Check to see if the package versions file exists
if [ ! -f $cache_file ]; then
    logger "$cache_file not found... aborting script"
    exit $abort
fi

# Create / update virtualenv
if [ ! -d $virtualenv_name ]; then
    virtualenv -p $(which python) $virtualenv_name
    source $virtualenv_name/bin/activate
    pip install twine
    deactivate
fi

# Get directory of current dir
venv_dir=`pwd`

# Change to specified branch and do git pull
git checkout $monitored_branch
git pull origin $monitored_branch

# For each python package (each setup.py file)
for setup_file in $(find "$venv_dir" -name setup.py); do
    # Get the name of the package
    pkg_name=`dirname $setup_file | xargs basename`
    cd $(dirname $setup_file)
    # And the version of the package
    current_version=`cat $setup_file | grep -i 'version="' | grep -o '[0-9]\+\.[0-9]\+\.[0-9]\+' | xargs`
    # Check whether the version in the cache file matches this current version
    prev_version=`cat $venv_dir/$cache_file | grep -w $pkg_name | awk '{print $2}' | xargs`
    if [ "$current_version" != "" ] && [ "$prev_version" != "$current_version" ]; then
        logger "$pkg_name current version $current_version doesn't match previous $prev_version"
        logger "Uploading to pypi..."
        pkg_path=`dirname $setup_file`
        # Activate Virtualenv
        cd "$venv_dir"
        source $virtualenv_name/bin/activate
        # Change directory to package
        cd "$pkg_path"
        # Build package
        python setup.py sdist
        # Capture build outcome
        outcome="$?"
        # Do upload if build was successful
        if [ "$outcome" == "0" ]; then
            cd "$pkg_path"
            $venv_dir/$virtualenv_name/bin/twine upload --repository-url https://pypi.zooxlabs.com/pypi dist/${pkg_name}-$current_version.tar.gz
        fi
        # Deactivate
        deactivate
        # Cleanup
        rm -rf dist/ 2> /dev/null
        upgrade_str="Do \`pip install $pkg_name --index-url $zoox_pypi --force-reinstall\` to update"
        if [ "$outcome" == "0" ]; then
            text="$pkg_name version $current_version now available on Zoox Pypi!\n$upgrade_str"
        else
            text="$pkg_name version $current_version did not build successfully. Not uploaded"
        fi
        curl -X POST \
-H 'Content-Type: application/json; charset=utf-8' \
--data "{\"channel\":\"$channel\", \"icon_emoji\":\"$icon_emoji\", \"username\":\"$bot_name\",
\"text\":\"$text\"}" \
https://hooks.slack.com/services/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
    else
        logger "$pkg_name is up-to-date"
    fi
    # Write current version with package to file
    if [ "$current_version" != "" ]; then
        echo "$pkg_name $current_version" >> $venv_dir/$temp_file
    fi
done

# Rename temp to cache file
echo "Updating cache file"
mv $venv_dir/$temp_file $venv_dir/$cache_file
