#!/usr/bin/env bash

base_path=$(cd $(dirname "${0}"); pwd)

usage () {
echo "Usage: create-binary-dist <name>"
}

if [ -z "${1}" ]; then
    usage
    exit 1
fi

case $1 in
backend|be)
    name="backend"
    setup_file="setup-gevent-all.py"
    binary_prefix="openmtc-all"
    ;;
gateway|gw)
    name="gateway"
    setup_file="setup-gevent-all.py"
    binary_prefix="openmtc-all"
    ;;
help)
    usage
    exit 0
    ;;
*) # other images will be detected by scanning setup files
    name="$1"
    setup_file="setup-${name}.py"
    binary_prefix="openmtc-${name}"
    ;;
esac

separator_line () {
counter=${1-80}
printf '%'${counter}'s\n' | tr ' ' '#'
}

# get setup file and set working dir
find_result=($(find ${base_path} -iname "${setup_file}"))

if [ ${#find_result[*]} -eq 0 ]; then
    echo "Setup file ${setup_file} not existing. Exiting Now!."
    exit 1
fi

if [ ${#find_result[*]} -gt 1 ]; then
    echo "Too many setup files matching the name. Exiting Now!."
    exit 1
fi

working_dir=$(dirname ${find_result[0]})

# get ids if chown is needed
chown_ids=${2}
if [[ ! ${chown_ids} =~ ^[0-9]{1,4}:[0-9]{1,4}$ ]]; then
    unset chown_ids
fi

################################################################################
# set target file
get_target_from_setup_file ()
{
# Each setup file is assumed to hold ".py" suffix, this gets
# removed here
local module_name=${setup_file%.py}

cd ${working_dir}
python - << END_OF_PYTHON
from importlib import import_module
setup = import_module('${module_name}', '${module_name}')
print("%s-%s" % (setup.SETUP_NAME, setup.SETUP_VERSION))
END_OF_PYTHON
}

# construct target file
target_file="$(get_target_from_setup_file).docker.tar.gz"
target_file="${working_dir}/dist/${target_file}"

################################################################################
# build binary_package
separator_line
printf "### Creating binary archive...\n"
printf "### Running \"python %s bdist\" now..." ${setup_file}
log_file="/tmp/${setup_file}_error.log"

# clean up before
rm -f ${target_file}
rm -rf ${working_dir}/build

# build
cd ${working_dir}
python ${setup_file} bdist --plat-name docker >/dev/null 2>${log_file}

# clean up after
rm -rf ${working_dir}/build
rm ${working_dir}/${setup_file}c
find ${base_path} -iname "*.egg-info" -exec rm -r "{}" \; 2> /dev/null

# check success
if [ -e ${target_file} ]; then
    printf "done\n"
else
    printf "error\n\n"
    cat ${log_file}
    exit 1
fi

rm ${log_file}

################################################################################
# clean binary_package
binary_archive="${working_dir}/dist/${binary_prefix}.docker.tar.gz"
printf "### Stripping .py files..."
cp ${target_file} ${binary_archive}
gzip -d ${binary_archive}
tar --wildcards --delete -f ${binary_archive%".gz"} "*.py"
gzip ${binary_archive%".gz"}
printf "done\n"
rm ${target_file}
printf "### Created binary archive at %s.\n" ${binary_archive}

################################################################################
# set correct permissions
if [ -n "${chown_ids}" ]; then
    chown -R "${chown_ids}" "${working_dir}/dist"
fi
