#!/bin/bash
# Check if the -n "nowheel" option was input
export nowheel='False'
while getopts n flag
do
    case "${flag}" in
        n) nowheel='True';;
    esac
done
# Fix project name in setup.py
mv -f setup.py setup.py.orig >& /dev/null
rm -f setup.py >& /dev/null
pypiname=`grep pypiname setup.py.orig | awk '{print $3}' | sed 's|["'\'']||g'`
name=`grep name setup.py.orig | grep -v pypiname | sed -nE 's/.*=\s*"(.*)".*/\1/p'`
if [ -z $pypiname ] || [ $pypiname == '' ]
then
  name=`grep name setup.py.orig | grep -v pypiname | sed -nE "s/.*=\s*'(.*)'.*/\1/p"`
fi
dirname=${PWD##*/}
echo "pypiname" ${pypiname}
if [ -z $pypiname ] || [ $pypiname == '' ]
then
  echo "using original name"
  pypiname=${name}
  cp -f setup.py.orig setup.py >& /dev/null
else
  echo "using new pypiname"
  cat setup.py.orig | sed 's/name="'${name}'"/name="'${pypiname}'"/g' > setup.py
fi
printf '%s\n' "Uploading new version to pypi as package '${pypiname}'"
\rm -R dist build ${pypiname}.egg-info ${name}.egg-info >& /dev/null
python setup.py sdist
# Make the wheel unless the "nowhell" -n flag was set
if [ $nowheel = 'False' ]
then
    python setup.py bdist_wheel --universal
fi
twine upload dist/*
# change setup.py back
mv -f setup.py.orig setup.py >& /dev/null
