#! /usr/bin/env bash

unset MISSING_APT_PACKAGES
export MISSING_APT_PACKAGES=()
SUGGESTED=()

APT_OK=$([[ -e $(type -fP apt) ]] && [[ -x $(type -fP apt | head -1) ]] && echo 'true' || echo 'false')

# TODO: Implement a test for specific Package Sources per package check
PACKAGE_SOURCES=$( \
  grep -h ^deb /etc/apt/sources.list /etc/apt/sources.list.d/* \
  | sed 's/\[.*\] //; s/^deb //' \
  | sort -u\
)

function print-result() {
  printf "%-30s: %-8s %s \n" "$1" "$2" "$3"
}
function test-print() {
  if [[ -n "$FAIL_EVERYTHING" || $(eval $1) ]]; then
    echo $3
  else
    echo $2
  fi
}

function safe-add() {
  SAVE_IFS="$IFS"
  IFS=':'
  eval "$1+=($2)"
  eval "$1=($(eval "echo $(printf '$IFS${%s[*]}$IFS' "$1")" | xargs -n1 echo | sort -u))"
  IFS="$SAVE_IFS"
  unset SAVE_IFS
}

KNOWN_REPOS=()
# REPO_<name>_HOSTNAME=Full.Qualified.Domain.Name.com
# REPO_<name>_PROTOCOL=http|https
# REPO_<name>_PATH=/ or /deeper/but/never/blank
function add-known-repo() {
  safe-add 'KNOWN_REPOS' "$1"

  eval "REPO_$1_HOSTNAME='$2'"
  eval "REPO_$1_PROTOCOL='${3:-http}'"
  eval "REPO_$1_PATH='${4:-/}'"
  eval "REPO_$1_KEYWORD='${5}'"
}

add-known-repo 'terraform'  'apt.releases.hashicorp.com' 'https'
add-known-repo 'terraform'  'apt.releases.hashicorp.com' 'https'
# add-known-repo 'docker'     'download.docker.com'        'https'
# add-known-repo 'anydesk'    'deb.anydesk.com'            'https'
# add-known-repo 'gcloud'     'packages.cloud.google.com'  'https'
# add-known-repo 'microsoft'  'packages.microsoft.com'     'https'
add-known-repo 'debian_sid' 'http.us.debian.org'         'http' '' 'sid'

# set | grep '^REPO'

# check-exist <Name> [path:default is $(type $1)] [test operator: default is -x] [Found note: default blank] [missing note: default blank] [reponame: default blank] 
function check-exist() {
  _RETURN_EVAL='true'
  _TEST_RESULT='Missing'
  _TEST_NAME=$1
  _TEST_PATH=${2:-$(type -fP $_TEST_NAME | head -1 2>/dev/null)}
  [[ -n "$_TEST_PATH" ]] && eval "[[ ${3:--x} ${_TEST_PATH// /\\ } ]]" && _TEST_RESULT='Found' || _RETURN_EVAL='false'
  [[ -n "$FAIL_EVERYTHING" ]] && _TEST_RESULT="-$_TEST_RESULT" && _RETURN_EVAL='false'
  eval $_RETURN_EVAL && _TEST_NOTE="${4}" || _TEST_NOTE="${5}"
  print-result "$_TEST_NAME" "$_TEST_RESULT" "$_TEST_NOTE"
  eval $_RETURN_EVAL
}

#### Output starts here
PROD_NAME=$( sudo dmidecode --type 200 2> /dev/null | tail +5 | tail -2 | head -1 | awk '{print $1}')

MACHINE_INFO_FORMAT='%-14s %-19s %-13s %-11s %s\n'
MACHINE_INFO_FIELDS=("Manufacturer" "Model family" "Model/MTM" "S/N" "BIOS Firmware")
printf "$MACHINE_INFO_FORMAT" "${MACHINE_INFO_FIELDS[@]}"
printf "$MACHINE_INFO_FORMAT" "$(
    sudo dmidecode -s system-manufacturer
  )" "$(sudo dmidecode -s system-family
  )" "${PROD_NAME:-$(
    sudo dmidecode -s system-product-name
  )}" "$(sudo dmidecode -s system-serial-number
  )" "$(sudo dmidecode -s bios-version)"
printf "  CPU: %s\n" "$(
    sudo dmidecode -s processor-version
  )"
echo ''

echo "Shell: $SHELL (availabe: $(echo $(cat /etc/shells | grep -v 'shells:' | sed "s/^\(.*\/\)*//" | sort -u)))"
echo ''

#_ALT_EDITOR=$( update-alternatives --get-selections | grep '^editor' | sed 's:^editor\W\+\w\+\W\+/:/:' )
_ALT_EDITOR=$( update-alternatives --query editor | grep '^Value:' | cut -d: -f2 | sed 's: *\(.*\) *:\1:g' )
print-result "System prefered editor" "$_ALT_EDITOR" "(Available: $(echo $(update-alternatives --query editor | grep Alternative: | cut -d: -f2 | sed 's/^\(.*\/\)//')))"
( echo $_ALT_EDITOR | grep "nano$" >/dev/null ) && echo "Recommended to run: update-alternatives --set editor $(type -fP nvim vim.basic vim.tiny vi | head -1)"
echo ''

print-result 'Executable `apt`' $(test-print $APT_OK "Found" "Missing") "$(test-print $APT_OK '' "$(printf 'repair by running:\n%-41sfix-apt.sh')" )"
echo ''
check-exist 'Byobu'     '/usr/bin/byobu-launch' || MISSING_APT_PACKAGES+=('byobu')
check-exist 'oh-my-posh'
check-exist '~/.poshtheme.omp.json' "~/.poshtheme.omp.json" "-r"
check-exist 'tmux'  || MISSING_APT_PACKAGES+=('tmux')
check-exist 'git'   || MISSING_APT_PACKAGES+=('git')
check-exist 'emacs' || MISSING_APT_PACKAGES+=('emacs')
check-exist 'monit' || MISSING_APT_PACKAGES+=('monit')
check-exist 'direnv' || MISSING_APT_PACKAGES+=('direnv')
check-exist 'terraform' '' '' ''       "$( \
    [[ -r /usr/share/keyrings/apt.releases.hashicorp.com.gpg ]] \
      && MISSING_APT_PACKAGES+=('terraform') \
      || echo                           'fix missing repos (See SUGGESTED below)' \
      )" \
  || SUGGESTED+=(
      'sz-add-my-apt-repos' '# followed by:' 'sudo apt install terraform', ''
  )
check-exist "setxkbmap" '' '' '(Optional)' \
  || MISSING_APT_PACKAGES+=('setxkbmap')
check-exist "chezmoi"   '' '' ''        'wget -O- chezmoi.io/get | bash # or
                                         # wget -O- lksz.me/dotfiles | bash'
check-exist "gcloud"    '' '' ''       "$( \
    [[ -r /usr/share/keyrings/apt.releases.hashicorp.com.gpg ]] \
      && MISSING_APT_PACKAGES+=('terraform') \
      || echo                           'fix missing repos (See SUGGESTED below)' \
      )" \
      || SUGGESTED+=( 'sz-add-my-apt-repos' '# followed by:' 'sudo apt install gcloud', '' )

check-exist 'bash completion'        '/usr/share/bash-completion/bash_completion' '-r'
check-exist 'CodeNewRoman Nerd Font' '~/.local/share/fonts/NF_CodeNewRoman'       '-d'
check-exist 'FiraCode Nerd Font'     '~/.local/share/fonts/NF_FiraCode'           '-d'
check-exist '~/bin'                  "~/bin"                                      '-d' '(Optional)'
check-exist '~/.local/bin'           "~/.local/bin"                               '-d' '(Optional)'
echo ""

[[ -n $SUGGESTED ]] && echo 'You might want to run the following commands:' && printf "  %s\n" "${SUGGESTED[@]}"

[[ -n $MISSING_APT_PACKAGES ]] && printf "There are some missing APT packages, run the following command line to add them:\n\tsudo apt install ${MISSING_APT_PACKAGES[*]}\n\n"