#!/bin/sh -e
#
# install_deb - install package from local/downloaded .deb-file and remove it
# can also infer a latest github release

loc="$(basename "$1")"
# shellcheck disable=SC2249
case "$1" in
  http*)
    wget --no-verbose -O "${loc}" "$@"
    ;;
  *.deb)
    loc="$1"
    ;;
  git*)
    domain="$1"
    shift
    arch=$(uname -m)
    case "${arch}" in
      x86_64) arch=amd64 ;;
      aarch64) arch=arm64 ;;
    esac
    result=$(curl -s "https://api.${domain}/repos/$1/$2/releases/latest" \
      | grep -o "http.*${3:-deb}" \
      | awk '{ print length(), $0 }' | sort -n | cut -d' ' -f 2-)
    # shellcheck disable=SC2312
    "$0" "$(echo "${result}" | grep "${arch}" | head -n 1 || echo "${result}")"
    exit "$?"
    ;;
esac
sudo dpkg --install "${loc}"
sudo apt-get --fix-broken install
sudo rm -v "${loc}"
