#!/bin/bash

# Higher-level purpose explained at the bottom of:
# https://github.com/iiab/iiab/blob/master/vars/default_vars.yml

# 2020-10-27: Most of the [15] variables require a command[*] to be run to
# establish the var's value.  WE DISPLAY ALL ERRORS / DIAGNOSTICS AND CONTINUE.
#
# [*] DOESN'T MATTER WHAT COMMAND: so long as it fails with Return Code != 0
# If RC == 0, var is forced from its default value here: (using cmd's output)

STAGE=0
OS="none"
VERSION_ID="none"    # Just a temp var, for: OS_VER="$OS-$VERSION_ID"
OS_VER="none"
IIAB_BRANCH="none"
IIAB_REMOTE_URL="none"
IIAB_RECENT_TAG="none"
IIAB_COMMIT="none"
RPI_MODEL="none"
DEVICETREE_MODEL="none"
ANSIBLE_VERSION="none"
PYTHON_VERSION="none"
PHP_VERSION="none"
DHCPCD="none"    # The last 3 conditioned on string output not RC.  SEE BELOW.
NETWORK_MANAGER="none"
SYSTEMD_NETWORKD="none"


# STAGE variable is for ./iiab-install which runs Ansible with iiab-stages.yml
# - fresh installs start at STAGE 0
# - interrupted installs record the last completed STAGE (1-9)
#
# We initialize it to '0' (zero) to cover the following 2 possibs: (1) iiab.env
# doesn't exist, or (2) iiab.env exists but fails to set STAGE=<something>
source /etc/iiab/iiab.env || true    # STAGE var auto-set, so no "if" required.

# /etc/lsb-release could also be grep'd.  But /etc/upstream-release/lsb-release
# on Linux Mint 20 caused grep of /etc/*elease to fail (on directory not file)
if tmp=$(grep ^ID= /etc/os-release); then
    OS=$(echo "$tmp" | cut -d= -f2)
    OS=${OS//\"/}    # Remove all '"'
fi
if [ -f /etc/rpi-issue ]; then
    OS="raspbian"    # For 64-bit Raspberry Pi OS which contains "ID=debian" as
fi    # of 2020: https://github.com/raspberrypi/Raspberry-Pi-OS-64bit/issues/6

if tmp=$(grep ^VERSION_ID= /etc/os-release); then
    VERSION_ID=$(echo "$tmp" | cut -d= -f2)
    # https://gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion
    VERSION_ID=${VERSION_ID//\"/}    # Remove all '"'
    [[ $OS == "ubuntu" ]] &&             # e.g. '22.04' -> '2204'
        VERSION_ID=${VERSION_ID//\./}    # Remove all '.'
    [[ $OS == "linuxmint" ]] &&         # e.g. '20.2' -> '20'
        VERSION_ID=${VERSION_ID%%.*}    # Remove all '.' & stuff to the right
fi
OS_VER="$OS-$VERSION_ID"

# Previously supported Linux distributions / versions:
    #"fedora-18"    | \
    #"fedora-22"    | \
    #"centos-7"     | \
    #"debian-8"     | \
    #"debian-9"     | \
    #"debian-10"    | \
    #"ubuntu-16"    | \
    #"ubuntu-17"    | \
    #"ubuntu-18"    | \
    #"ubuntu-19"    | \
    #"ubuntu-2004"  | \
    #"ubuntu-2104"  | \
    #"ubuntu-2110"  | \
    #"linuxmint-20" | \
    #"raspbian-8"   | \
    #"raspbian-9"   | \
    #"raspbian-10"  | \

# 2021-09-27: With Debian 12 (Bookworm) pre-releases, please manually add
# this line to its /etc/os-release before installing IIAB: VERSION_ID="12"

case $OS_VER in
    "debian-11"    | \
    "debian-12"    | \
    "ubuntu-2204"  | \
    "ubuntu-2210"  | \
    "ubuntu-2304"  | \
    "ubuntu-2310"  | \
    "linuxmint-21" | \
    "raspbian-11"  | \
    "raspbian-12")
        ;;
    *) echo -e "\n\e[41;1mOS '$OS_VER' IS NOT SUPPORTED. Please read:\e[0m\n\n\e[1mhttps://github.com/iiab/iiab/wiki/IIAB-Platforms\e[0m\n" ; exit 1    # Used by /opt/iiab/iiab/iiab-install
        ;;
esac


# These next 4 help indicate what version of IIAB
tmp=$(git rev-parse --abbrev-ref HEAD) &&
    IIAB_BRANCH=$tmp

tmp=$(git config branch.$IIAB_BRANCH.remote) && {
    if [[ $tmp =~ ^"https://" ]]; then
        IIAB_REMOTE_URL=$tmp
    else
        IIAB_REMOTE_URL=$(git config remote.$tmp.url)
    fi
}

tmp=$(git describe --tags --abbrev=0) &&
    IIAB_RECENT_TAG=$tmp

tmp=$(git rev-parse --verify HEAD) &&
    IIAB_COMMIT=$tmp


grep -iq raspberry /proc/device-tree/model &&
    RPI_MODEL=$(grep -ai raspberry /proc/device-tree/model | tr -d '\0')

# /proc/device-tree/model e.g. 'Parallels ARM Virtual Machine' identical to...
# /sys/firmware/devicetree/base/model (also true on RPi hardware!)

# tr -d '\0' ...strips out its null byte, for cleaner output (PR #3086)

tmp=$(tr -d '\0' < /proc/device-tree/model) &&
    DEVICETREE_MODEL=$tmp


tmp=$(ansible --version) &&
    ANSIBLE_VERSION=$(echo "$tmp" | head -1 | cut -f 2- -d " " | sed 's/.* \([^ ]*\)\].*/\1/')
    # Above works with 'ansible [core 2.11.0rc2]' -- these old ways do not:
    #ANSIBLE_VERSION=$(echo "$tmp" | head -1 | awk '{print $2}')
    #ANSIBLE_VERSION=$(echo "$tmp" | head -1 | sed -e 's/.* //')

if tmp=$(python3 -c 'from sys import version_info; print("%s.%s" % (version_info.major, version_info.minor));'); then
    PYTHON_VERSION=$tmp
else
    echo -e "\e[1m\nPython 3 is REQUIRED for Internet-in-a-Box.  You might want to run:\n\nsudo apt install python3\n\e[0m"
    exit 1
fi

tmp=$(apt list php) &&
    PHP_VERSION=$(echo $tmp | grep -Po '[0-9]+\.[0-9]+' | head -1)
# Extracts the first (topmost, leftmost) MAJOR.MINOR, even if not yet installed
# Safer than: echo $tmp | grep php | head -1 | sed 's/.*://; s/[^0-9.].*//')
# https://stackoverflow.com/questions/16675179/how-to-use-sed-to-extract-substring/16675391#16675391


# THE LAST 3 BELOW ARE DIFFERENT as "systemctl is-enabled" unhelpfully returns
# the same error code (i.e. 1) REGARDLESS whether the service is (A) disabled
# or (B) doesn't exist. SO WE TEST THE STRING OUTPUT INSTEAD OF THE RETURN CODE

tmp=$(systemctl is-enabled dhcpcd)
[[ $tmp != "" ]] &&
    DHCPCD=$tmp
#[[ $tmp ]] && DHCPCD=$tmp    # Short Ain't Sweet (less understandable)

# is_redhat uses "NetworkManager".  Debian 7 & Ubuntu 14.10 required
# "network-manager" (prior to 2015/systemd).  Ubuntu 20.10 dropped the
# legacy symlink from "network-manager.service" to "NetworkManager.service"
tmp=$(systemctl is-enabled NetworkManager)
[[ $tmp != "" ]] &&
    NETWORK_MANAGER=$tmp

tmp=$(systemctl is-enabled systemd-networkd)
[[ $tmp != "" ]] &&
    SYSTEMD_NETWORKD=$tmp


# https://en.wikipedia.org/wiki/Here_document
cat <<EOF
{"stage"                  : "$STAGE",
"os"                      : "$OS",
"os_ver"                  : "$OS_VER",
"iiab_branch"             : "$IIAB_BRANCH",
"iiab_remote_url"         : "$IIAB_REMOTE_URL",
"iiab_recent_tag"         : "$IIAB_RECENT_TAG",
"iiab_commit"             : "$IIAB_COMMIT",
"rpi_model"               : "$RPI_MODEL",
"devicetree_model"        : "$DEVICETREE_MODEL",
"ansible_version"         : "$ANSIBLE_VERSION",
"python_version"          : "$PYTHON_VERSION",
"php_version"             : "$PHP_VERSION",
"dhcpcd"                  : "$DHCPCD",
"network_manager"         : "$NETWORK_MANAGER",
"systemd_networkd"        : "$SYSTEMD_NETWORKD"}
EOF
