#!/usr/bin/env bash
# This script was generated by bashly 1.3.3 (https://bashly.dev)
# Modifying it manually is not recommended

if ((BASH_VERSINFO[0] < 4 || (BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] < 2))); then
  printf "bash version 4.2 or higher is required\n" >&2
  exit 1
fi

root_command() {
  # Settings
  source_url=${args[source]}
  publisher=${args[publisher]}
  # Flags
  no_call=${args[--no-call]}
  dry_run=${args[--dry-run]}

  REQS="wget apt-transport-https curl gpg"

  function do_call() {
      if [[ $dry_run ]]; then
          echo -e "### DRY RUN: \n$1"
      else
          $1
      fi
  }

  function get_distribution {
      if [ -f /etc/os-release ]; then
          . /etc/os-release
          OS=$NAME
          VER=$VERSION_ID
      elif type lsb_release >/dev/null 2>&1; then
          OS=$(lsb_release -si)
          VER=$(lsb_release -sr)
      elif [ -f /etc/lsb-release ]; then
          . /etc/lsb-release
          OS=$DISTRIB_ID
          VER=$DISTRIB_RELEASE
      elif [ -f /etc/debian_version ]; then
          OS=Debian
          VER=$(cat /etc/debian_version)
      elif [ -f /etc/SuSe-release ]; then
          OS=SEL
      elif [ -f /etc/redhat-release ]; then
          OS=RedHat
      else
          OS=$(uname -s)
          VER=$(uname -r)
      fi
  }

  echo "### Installer for InvenTree - source: $publisher/$source_url"

  # Check if os and version is supported
  get_distribution
  echo "### Detected distribution: $OS $VER"
  SUPPORTED=true          # is this OS supported?

  DIST_OS=${OS,,}
  DIST_VER=$VER

  case "$OS" in
      Ubuntu)
          if [[ $VER == "24.04" ]]; then
              SUPPORTED=true
          elif [[ $VER == "22.04" ]]; then
              SUPPORTED=true
          elif [[ $VER == "20.04" ]]; then
              SUPPORTED=true
          else
              SUPPORTED=false
          fi
          ;;
      "Debian GNU/Linux" | "debian gnu/linux" | Raspbian)
          if [[ $VER == "12" ]]; then
              SUPPORTED=true
          elif [[ $VER == "11" ]]; then
              SUPPORTED=true
          elif [[ $VER == "10" ]]; then
              SUPPORTED=true
          else
              SUPPORTED=false
          fi
          DIST_OS=debian
          ;;
      *)
          echo "### Distribution not supported"
          SUPPORTED=false
          ;;
  esac

  if [[ $SUPPORTED != "true" ]]; then
      echo "This OS is currently not supported."
      echo "Please install manually using https://docs.inventree.org/en/stable/start/install/"
      echo "or check https://github.com/inventree/InvenTree/issues/3836 for packaging for your OS."
      echo "If you think this is a bug please file an issue at"
      echo "https://github.com/inventree/InvenTree/issues/new?template=install.yaml"

      exit 1
  fi

  echo "### Installing required packages for download"
  for pkg in $REQS; do
      if dpkg-query -W -f'${Status}' "$pkg" 2>/dev/null | grep -q "ok installed"; then
          true
      else
          do_call "sudo apt-get -yqq install $pkg"
      fi
  done

  echo "### Getting and adding key"
  curl -fsSL https://dl.packager.io/srv/$publisher/InvenTree/key | gpg --dearmor | tee /etc/apt/trusted.gpg.d/pkgr-inventree.gpg > /dev/null
  echo "### Adding package source"
  SOURCE_URL="deb [signed-by=/etc/apt/trusted.gpg.d/pkgr-inventree.gpg] https://dl.packager.io/srv/deb/$publisher/InvenTree/$source_url/$DIST_OS $DIST_VER main"
  echo "$SOURCE_URL" | tee /etc/apt/sources.list.d/inventree.list > /dev/null
  echo "### Updating package lists"
  do_call "sudo apt-get update"

  # Set up environment for install
  echo "### Setting installer args"
  if [[ $no_call ]]; then
      do_call "export NO_CALL=true"
  fi

  echo "### Installing InvenTree"
  do_call "sudo apt-get install inventree -y"

  echo "### Install done!"

}

version_command() {
  echo "$version"
}

install.sh_usage() {
  printf "install.sh - Interactive installer for InvenTree\n\n"

  printf "%s\n" "Usage:"
  printf "  install.sh [SOURCE] [PUBLISHER] [OPTIONS]\n"
  printf "  install.sh --help | -h\n"
  printf "  install.sh --version | -v\n"
  echo

  if [[ -n "$long_usage" ]]; then
    printf "%s\n" "Options:"

    printf "  %s\n" "--no-call, -n"
    printf "    Do not call outside APIs (only functionally needed)\n"
    echo

    printf "  %s\n" "--dry-run, -d"
    printf "    Dry run (do not install anything)\n"
    echo

    printf "  %s\n" "--help, -h"
    printf "    Show this help\n"
    echo
    printf "  %s\n" "--version, -v"
    printf "    Show version number\n"
    echo

    printf "%s\n" "Arguments:"

    printf "  %s\n" "SOURCE"
    printf "    Package source that should be used\n"
    printf "    %s\n" "Allowed: stable, master, main"
    printf "    %s\n" "Default: stable"
    echo

    printf "  %s\n" "PUBLISHER"
    printf "    Publisher that should be used\n"
    printf "    %s\n" "Default: inventree"
    echo

    printf "%s\n" "Examples:"
    printf "  install\n"
    printf "  install master --no-call\n"
    printf "  install master matmair --dry-run\n"
    echo

  fi
}

normalize_input() {
  local arg passthru flags
  passthru=false

  while [[ $# -gt 0 ]]; do
    arg="$1"
    if [[ $passthru == true ]]; then
      input+=("$arg")
    elif [[ $arg =~ ^(--[a-zA-Z0-9_\-]+)=(.+)$ ]]; then
      input+=("${BASH_REMATCH[1]}")
      input+=("${BASH_REMATCH[2]}")
    elif [[ $arg =~ ^(-[a-zA-Z0-9])=(.+)$ ]]; then
      input+=("${BASH_REMATCH[1]}")
      input+=("${BASH_REMATCH[2]}")
    elif [[ $arg =~ ^-([a-zA-Z0-9][a-zA-Z0-9]+)$ ]]; then
      flags="${BASH_REMATCH[1]}"
      for ((i = 0; i < ${#flags}; i++)); do
        input+=("-${flags:i:1}")
      done
    elif [[ "$arg" == "--" ]]; then
      passthru=true
      input+=("$arg")
    else
      input+=("$arg")
    fi

    shift
  done
}

parse_requirements() {

  while [[ $# -gt 0 ]]; do
    key="$1"
    case "$key" in
      --version | -v)
        version_command
        exit
        ;;

      --help | -h)
        long_usage=yes
        install.sh_usage
        exit
        ;;

      *)
        break
        ;;

    esac
  done

  action="root"

  while [[ $# -gt 0 ]]; do
    key="$1"
    case "$key" in

      --no-call | -n)

        args['--no-call']=1
        shift
        ;;

      --dry-run | -d)

        args['--dry-run']=1
        shift
        ;;

      -?*)
        printf "invalid option: %s\n" "$key" >&2
        exit 1
        ;;

      *)

        if [[ -z ${args['source']+x} ]]; then
          args['source']=$1
          shift

        elif [[ -z ${args['publisher']+x} ]]; then
          args['publisher']=$1
          shift
        else
          printf "invalid argument: %s\n" "$key" >&2
          exit 1
        fi

        ;;

    esac
  done

  [[ -n ${args['source']:-} ]] || args['source']="stable"
  [[ -n ${args['publisher']:-} ]] || args['publisher']="inventree"

  if [[ -n ${args['source']:-} ]] && [[ ! ${args['source']:-} =~ ^(stable|master|main)$ ]]; then
    printf "%s\n" "source must be one of: stable, master, main" >&2
    exit 1
  fi

}

initialize() {
  declare -g version="2.0"
  set -e

}

run() {

  declare -g long_usage=''
  declare -g -A args=()
  declare -g -A deps=()
  declare -g -a env_var_names=()
  declare -g -a input=()

  normalize_input "$@"
  parse_requirements "${input[@]}"

  case "$action" in
    "root") root_command ;;
  esac
}

command_line_args=("$@")
initialize
run "${command_line_args[@]}"
