# shellcheck shell=ash

PYDROID_HOME="/data/local/pydroid"

install_pydroid() {
  if [ ! -f "force_install" ]; then
    ui_print "! PyDroid is no longer maintained"
    ui_print "! Please use Py2Droid instead: https://github.com/Mrakorez/py2droid"
    ui_print ""
    ui_print "! To proceed with this installation anyway, create a 'force_install' file"
    ui_print "! in the root of the zip archive"
    abort
  fi

  for dir in .tmp .cache .config .local/share .local/state; do
    mkdir -p "${PYDROID_HOME}/${dir}"
  done

  case "${ARCH}" in
    "arm64")
      tar -xf "python/arm64.tar.xz" -C "${PYDROID_HOME}" \
        --strip-components 1
      ;;
    "arm")
      tar -xf "python/arm.tar.xz" -C "${PYDROID_HOME}" \
        --strip-components 1
      ;;
    *)
      . ./uninstall.sh
      abort "! Your device architecture is not supported"
      ;;
  esac

  tar -xf "python/common.tar.xz" -C "${PYDROID_HOME}" \
    --strip-components 1

  (
    . ./env.sh
    exec python3 system/bin/pydroid-update-bin 2>/dev/null
  )

  mv -f env.sh "${PYDROID_HOME}"
}

set_permissions() {
  set_perm_recursive "system/bin" 0 0 0755 0744
  set_perm_recursive "${PYDROID_HOME}/usr/bin" 0 0 0755 0744
  set_perm_recursive "${PYDROID_HOME}/usr/lib" 0 0 0755 0644
  set_perm_recursive "${PYDROID_HOME}/usr/include" 0 0 0755 0644
}

cleanup() {
  rm -rf CHANGELOG.md LICENSE README.md python force_install
}

main() {
  cd "${MODPATH}" ||
    abort "! Cannot cd to ${MODPATH}"

  install_pydroid
  set_permissions
  cleanup
}

main
