#!/usr/bin/bash

arch=$(uname -m)
install_mpm=true
python=python3

if [[ -z "$BIN_PATH" ]]; then
  BIN_PATH=/usr/bin
fi

report() {
  echo "mei_installer: $@"
}

SUPPORTED=("x86_64" "armv7l" "aarch64" "e2k")

if [[ ! " ${SUPPORTED[*]} " =~ " $arch " ]]; then
  report "error: this system ($arch) is not supported."
  exit 1
fi

LATEST_MEI="https://files.txlyre.website/d/software/mei/latest_$arch/mei"
LATEST_MPM="https://files.txlyre.website/d/software/mpm/latest/mpm.py"

if [ "$BIN_PATH" = "/usr/bin" ] && ! [ "${EUID:-$(id -u)}" -eq 0 ]; then
  report "error: this script must be run as root."
  exit 1
fi

if ! command -v git >/dev/null 2>&1; then
  report "warning: Git is not available."
  install_mpm=false
fi

if ! command -v $python >/dev/null 2>&1; then
  python=python
fi

if $install_mpm && ! command -v $python >/dev/null 2>&1 || ! $python -c "import sys; sys.exit(0 if sys.version_info.major >= 3 and sys.version_info.minor >= 5 else 1)"; then
  report "warning: Python>=3.5 is not available."
  install_mpm=false
fi

if ! $install_mpm; then
  report "warning: MPM will not be installed."
fi

if ! [[ -z "$DOWNLOADER" ]]; then
  downloader="$DOWNLOADER"
elif [ -x "$(command -v wget)" ]; then
  downloader=wget
elif [ -x "$(command -v curl)" ]; then
  downloader=curl -f -O
else
  report "error: neither 'wget' nor 'curl' is available and no custom command is given."
  exit 1
fi

download() {
  $downloader "$@"

  if [ "$?" -ne 0 ]; then
    report "error: download($@) failed."
    exit 1
  fi
}

report "download mei..."
download $LATEST_MEI

if $install_mpm; then
  report "download mpm..."

  download $LATEST_MPM
fi

report "install mei..."

chmod +x mei
mv mei "$BIN_PATH"

if $install_mpm; then
  report "install mpm..."
 
  chmod +x mpm.py
  mv mpm.py "$BIN_PATH/mpm"
fi

report "done!"
