#!/usr/bin/env bash

# Accepts a version string and prints it incremented by one.
# Usage: increment_version <version> [<position>] [<leftmost>]
increment_version() {
  declare -a part=(${1//\./ })
  declare new
  declare -i carry=1

  for ((CNTR = ${#part[@]} - 1; CNTR >= 0; CNTR -= 1)); do
    len=${#part[CNTR]}
    new=$((part[CNTR] + carry))
    [ ${#new} -gt $len ] && carry=1 || carry=0
    [ $CNTR -gt 0 ] && part[CNTR]=${new: -len} || part[CNTR]=${new}
  done

  new="${part[*]}"
  if [[ "$OSTYPE" == "linux-gnu"* ]]; then
    echo -e "${new// /.}"
  elif [[ "$OSTYPE" == "darwin"* ]]; then
    echo "${new// /.}"
  elif [[ "$OSTYPE" == "cygwin" ]]; then
    echo "not correct system - cygwin detected"
    exit
  fi
}

pub_ver() {
  VERSION=$(cat version)
  increment_version $VERSION >version
  VERSION=$(cat version)

  python3.11 -m pip install --user --upgrade setuptools wheel
  # python3 -m pip install --upgrade setuptools wheel
  # python3 -m readme_renderer README.rst -o ./html/README.html
  sudo python3.11 setup.py clean sdist bdist_wheel

  echo "========================================================="
  echo "now uploading the content to pypi"
  python3.11 -m twine upload dist/* --verbose

  echo "please update the package by using this command"
  echo "pip3 install machineroom==$VERSION"
  echo "wait 30 seconds until it gets uploaded online..."
  # echo "ready and install it again.."
  sudo rm -rf dist
}

git_update() {
  git add .
  git commit -m "auto patched"
  git push
}

pub_ver
git_update
