#!/bin/bash
#
# shellcheck disable=SC1090,SC1091,SC2010,SC2016,SC2046,SC2086,SC2154,SC2174
#
# Copyright (c) 2015-2026 openmediavault plugin developers
# Copyright (c) 2017-2020 Armbian Developers
#
# This file is licensed under the terms of the GNU General Public
# License version 2. This program is licensed "as is" without any
# warranty of any kind, whether express or implied.
#
# Ideas/code used from:
# https://github.com/armbian/config/blob/master/debian-software
# https://forum.openmediavault.org/index.php/Thread/25062-Install-OMV5-on-Debian-10-Buster/
#

logfile="/root/omv_install.log"
scriptversion="3.1.0"

exec > >(stdbuf -oL -eL tee -a "${logfile}") 2>&1

trap 'rc=$?; echo "=== END $(date -Is) rc=$rc ==="; exit $rc' EXIT

_log()
{
  msg=${1}
  echo "[$(date +'%Y-%m-%d %H:%M:%S%z')] [omvinstall] ${msg}"
}

ag_install() {
  local mode="${1:-}"
  shift || true
  local pkgs=("$@")
  local rc

  case "${mode}" in
    complex)
      local aptFlags=(--yes --auto-remove --show-upgraded --allow-downgrades \
                      --allow-change-held-packages --no-install-recommends)
      apt-get "${aptFlags[@]}" install "${pkgs[@]}"
      ;;

    normal)
      apt-get --yes --no-install-recommends install "${pkgs[@]}"
      ;;

    purge)
      apt-get --yes --autoremove purge "${pkgs[@]}"
      ;;

    reinstall)
      apt-get --yes --no-install-recommends --reinstall install "${pkgs[@]}"
      ;;

    fix-broken)
      apt-get --yes --fix-broken install
      ;;

    rupdate)
      apt-get --allow-releaseinfo-change update
      ;;

    update)
      apt-get update
      ;;

    *)
      apt-get --yes --no-install-recommends install -t "${mode}" "${pkgs[@]}"
      ;;
  esac

  return $?
}


_log "script version :: ${scriptversion}"

if [[ $(id -u) -ne 0 ]]; then
  echo "This script must be executed as root or using sudo."
  exit 99
fi

systemd="$(ps --no-headers -o comm 1)"
if [ ! "${systemd}" = "systemd" ]; then
  echo "This system is not running systemd.  Exiting..."
  exit 100
fi

if dpkg -l | grep -Eqw "gdm3|sddm|lxdm|xdm|lightdm|slim|wdm"; then
  echo "This system is running a desktop environment!"
  echo "Please use a Lite version of the image or"
  echo "do not choose to install a desktop environment."
  echo "This install is not supported."
  echo "Search the forum for more info - https://forum.openmediavault.org"
  echo "Exiting..."
  exit 101
fi

if [ ! -L "/sbin" ] || [ ! -L "/bin" ]; then
  echo "The /usr directories seem not to be migrated. Please check the"
  echo "following pages for more information:"
  echo "- https://wiki.debian.org/UsrMerge"
  echo "- https://www.freedesktop.org/wiki/Software/systemd/TheCaseForTheUsrMerge"
  echo "Exiting..."
  exit 102
fi

if [ -f "/.dockerenv" ]; then
  echo "Docker detected. OMV does not work in Docker!"
  exit 103
fi

if grep -q 'machine-lxc' /proc/1/cgroup; then
  echo "LXC detected. OMV does not work in LXC!"
  exit 104
fi

declare -i armbian=0
declare -i cfg=0
declare -i ipv6=0
declare -i nm=0
declare -i rpi=0
declare -i skipFlash=0
declare -i skipNet=0
declare -i skipReboot=0
declare -i useMirror=0
declare -i version

declare -l codename
declare -l omvCodename
declare -l omvInstall=""
declare -l omvextrasInstall=""

declare gov=""
declare minspd=""
declare maxspd=""

aptclean="/usr/sbin/omv-aptclean"
crda="/etc/default/crda"
defaultGovSearch="^CONFIG_CPU_FREQ_DEFAULT_GOV_"
flash="flashmemory"
forceIpv4="/etc/apt/apt.conf.d/99force-ipv4"
ioniceCron="/etc/cron.d/make_nas_processes_faster"
ioniceScript="/usr/sbin/omv-ionice"
mirror="https://mirrors.tuna.tsinghua.edu.cn"
omvKey="/usr/share/keyrings/openmediavault-archive-keyring.gpg"
omvRepo="http://packages.openmediavault.org/public"
omvKeyUrl="${omvRepo}/archive.key"
omvSources="/etc/apt/sources.list.d/openmediavault.list"
resolvTmp="/root/resolv.conf"
rfkill="/usr/sbin/rfkill"
smbOptions=""
url="https://github.com/OpenMediaVault-Plugin-Developers/packages/raw/master"
vsCodeList="/etc/apt/sources.list.d/vscode.list"
wpaConf="/etc/wpa_supplicant/wpa_supplicant.conf"

export DEBIAN_FRONTEND=noninteractive
export APT_LISTCHANGES_FRONTEND=none
export LANG=C.UTF-8
export LANGUAGE=C
export LC_ALL=C.UTF-8

if [ -f /etc/armbian-release ]; then
  . /etc/armbian-release
  armbian=1
  _log "Armbian"
fi

while getopts "fhimnr" opt; do
  _log "option ${opt}"
  case "${opt}" in
    f)
      skipFlash=1
      ;;
    h)
      echo "Use the following flags:"
      echo "  -f"
      echo "    to skip the installation of the flashmemory (omv7) / writecache (omv8) plugin"
      echo "  -i"
      echo "    enable using IPv6 for apt"
      echo "  -m"
      echo "    to repo mirror from ${mirror}"
      echo "  -n"
      echo "    to skip the network setup"
      echo "  -r"
      echo "    to skip reboot"
      echo ""
      echo "Examples:"
      echo "  install"
      echo "  install -f"
      echo "  install -n"
      echo ""
      echo "Notes:"
      echo "  This script will always install:"
      echo "    - OMV 7.x (sandworm) on Debian 12 (Bookworm)"
      echo "    - OMV 8.x (synchrony) on Debian 13 (Trixie)"
      echo ""
      exit 100
      ;;
    i)
      ipv6=1
      ;;
    m)
      useMirror=1
      omvRepo="${mirror}/OpenMediaVault/public"
      ;;
    n)
      skipNet=1
      ;;
    r)
      skipReboot=1
      ;;
    \?)
      _log "Invalid option: -${OPTARG}"
      ;;
  esac
done

_log "Starting ..."

# Fix permissions on / if wrong
_log "Current / permissions = $(stat -c %a /)"
chmod -v g-w,o-w /
_log "New / permissions = $(stat -c %a /)"

# if ipv6 is not enabled, create apt config file to force ipv4
if [ ${ipv6} -ne 1 ]; then
  _log "Forcing IPv4 only for apt..."
  echo 'Acquire::ForceIPv4 "true";' > ${forceIpv4}
fi

if [ -f "/usr/libexec/config-rtl8367rb.sh" ]; then
  _log "Skipping network because swconfig controlled switch found."
  skipNet=1
fi

_log "Updating repos before installing..."
echo 'Acquire::Languages "none";' | tee /etc/apt/apt.conf.d/99no-translations
ag_install rupdate

_log "Installing lsb_release..."
ag_install reinstall lsb-release

arch="$(dpkg --print-architecture)"
_log "Arch :: ${arch}"

codename="$(lsb_release --codename --short)"
_log "Codename :: ${codename}"

case ${codename} in
  bookworm)
    omvCodename="sandworm"
    version=7
    if [[ ! ${arch} =~ ^(arm64|armhf|amd64|i386)$ ]]; then
      _log "Unsupported architecture :: ${arch}"
      exit 5
    fi
    cpuPkg="cpufrequtils"
    cpuState="cpufrequtils"
    cpuFreqDef="/etc/default/cpufrequtils"
    ;;

  trixie)
    omvCodename="synchrony"
    version=8
    flash="writecache"
    if [[ ! ${arch} =~ ^(arm64|amd64)$ ]]; then
      _log "Unsupported architecture :: ${arch}"
      exit 5
    fi
    cpuPkg="linux-cpupower"
    cpuState="cpupower"
    cpuFreqDef="/etc/default/cpupower"
    ;;
  *)
    _log "Unsupported version.  Only 12 (Bookworm) and 13 (Trixie) are supported.  Exiting..."
    exit 1
  ;;
esac
_log "Debian :: ${codename}"
_log "${omvCodename} :: ${version}"

hostname="$(hostname --short)"
_log "Hostname :: ${hostname}"
domainname="$(hostname --domain)"
_log "Domain name :: ${domainname}"
tz="$(timedatectl show --property=Timezone --value)"
_log "timezone :: ${tz}"

regex='[a-zA-Z]([-a-zA-Z0-9]{0,61}[a-zA-Z0-9])'
if [[ ! ${hostname} =~ ${regex} ]]; then
    _log "Invalid hostname.  Exiting..."
    exit 6
fi

_log "Copying /etc/resolv.conf to ${resolvTmp} ..."
cp -fv /etc/resolv.conf "${resolvTmp}"
_log "$(cat /etc/resolv.conf)"

if grep -rq raspberrypi.org /etc/apt/*; then
  rpivers="$(awk '$1 == "Revision" { print $3 }' /proc/cpuinfo)"
  _log "RPi revision code :: ${rpivers}"
  rpi=1
fi

# remove armbian netplan file if found
anp="/etc/netplan/armbian-default.yaml"
if [ -e "${anp}" ]; then
  _log "Removing Armbian netplan file..."
  rm -fv "${anp}"
fi

dpkg -P udisks2

_log "Install prerequisites..."
ag_install normal gnupg wget

if [ ${armbian} -eq 1 ]; then
  systemctl unmask systemd-networkd.service
  # save off cpuFreq settings before installing the openmediavault
  if [ -f "${cpuFreqDef}" ]; then
    . ${cpuFreqDef}
    gov="${GOVERNOR}"
    minspd="${MIN_SPEED}"
    maxspd="${MAX_SPEED}"
  fi
fi

# make sure ssh is enabled
systemctl enable ssh.service

# install openmediavault if not installed already
omvInstall=$(dpkg -l | awk '$2 == "openmediavault" { print $1 }')
if [[ ! "${omvInstall}" == "ii" ]]; then
  _log "Installing openmediavault required packages..."
  if ! ag_install normal postfix; then
    _log "failed installing postfix"
    sed -i '/^myhostname/d' /etc/postfix/main.cf
    if ! ag_install fix-broken; then
      _log "failed installing postfix and unable to fix"
      exit 2
    fi
  fi

  _log "Adding openmediavault repo and key..."
  echo "deb [signed-by=${omvKey}] ${omvRepo} ${omvCodename} main" | tee ${omvSources}
  wget --quiet --output-document=- "${omvKeyUrl}" | gpg --dearmor --yes --output "${omvKey}"

  _log "Updating repos..."
  if ! ag_install update; then
    _log "failed to update apt repos."
    exit 2
  fi

  _log "Install openmediavault-keyring..."
  if ! ag_install normal openmediavault-keyring; then
    _log "failed to install openmediavault-keyring package."
    exit 2
  fi

  monitInstall=$(dpkg -l | awk '$2 == "monit" { print $1 }')
  if [[ ! "${monitInstall}" == "ii" ]]; then
    if ! ag_install normal monit; then
      _log "failed installing monit"
      exit 2
    fi
  fi

  saltInstall=$(dpkg -l | awk '$2 == "salt-minion" { print $1 }')
  if [[ ! "${saltInstall}" == "ii" ]] && [ ${version} -eq 8 ]; then
    if ! ag_install normal salt-common salt-minion python3-samba; then
      _log "failed installing salt"
      exit 2
    fi
  fi

  omvsaltInstall=$(dpkg -l | awk '$2 == "openmediavault-salt" { print $1 }')
  if [[ ! "${omvsaltInstall}" == "ii" ]] && [ ${version} -eq 8 ]; then
    if ! ag_install normal openmediavault-salt; then
      _log "failed installing openmediavault-salt"
      exit 2
    fi
  fi

  _log "Installing openmediavault..."
  if ! ag_install complex openmediavault; then
    _log "failed to install openmediavault package."
    exit 2
  fi

  omv-confdbadm populate
  omv-salt deploy run hosts
fi
_log "Testing DNS..."
if ! ping -4 -q -c2 omv-extras.org 2>/dev/null; then
  _log "DNS failing to resolve.  Fixing ..."
  if [ -f "${resolvTmp}" ]; then
    _log "Reverting /etc/resolv.conf to saved copy ..."
    rm -fv /etc/resolv.conf
    cp -v "${resolvTmp}" /etc/resolv.conf
  fi
fi

# check if openmediavault is install properly
omvInstall=$(dpkg -l | awk '$2 == "openmediavault" { print $1 }')
if [[ ! "${omvInstall}" == "ii" ]]; then
  _log "openmediavault package failed to install or is in a bad state."
  exit 3
fi

. /etc/default/openmediavault
. /usr/share/openmediavault/scripts/helper-functions

if [ ${version} -eq 8 ]; then
  /usr/sbin/omv-rpc -u admin "powermgmt" "set" '{"cpufreq":false,"powerbtn":"nothing","standbymode":"poweroff"}'
fi

# remove backports from sources.list to avoid duplicate sources warning
sed -i "/\(trixie\|bookworm\)-backports/d" /etc/apt/sources.list

if [ ${rpi} -eq 1 ]; then
  if [ ! "${arch}" = "arm64" ]; then
    omv_set_default "OMV_APT_USE_OS_SECURITY" false true
  fi
  omv_set_default "OMV_APT_USE_KERNEL_BACKPORTS" false true
fi

# change repos if useMirror is specified
if [ ${useMirror} -eq 1 ]; then
  _log "Changing repos to mirror from ${mirror} ..."
  omv_set_default OMV_APT_REPOSITORY_URL "${mirror}/OpenMediaVault/public" true
  omv_set_default OMV_APT_ALT_REPOSITORY_URL "${mirror}/OpenMediaVault/packages" true
  omv_set_default OMV_APT_KERNEL_BACKPORTS_REPOSITORY_URL "${mirror}/debian" true
  omv_set_default OMV_APT_SECURITY_REPOSITORY_URL "${mirror}/debian-security" true
  omv_set_default OMV_EXTRAS_APT_REPOSITORY_URL "${mirror}/OpenMediaVault/openmediavault-plugin-developers" true
  omv_set_default OMV_DOCKER_APT_REPOSITORY_URL "${mirror}/docker-ce/linux/debian" true
  omv_set_default OMV_PROXMOX_APT_REPOSITORY_URL "${mirror}/proxmox/debian" true

  # update pillar default list - /srv/pillar/omv/default.sls
  omv-salt stage run prepare

  # update config files
  omv-salt deploy run apt

  # ensure CPU power package is present (varies by OMV version)
  _log "Installing CPU power package: ${cpuPkg} ..."
  ag_install normal ${cpuPkg}
fi

# install omv-extras
_log "Downloading omv-extras.org plugin for openmediavault ${version}.x ..."
file="openmediavault-omvextrasorg_latest_all${version}.deb"

if [ -f "${file}" ]; then
  rm "${file}"
fi
wget ${url}/${file}
if [ -f "${file}" ]; then
  if ! dpkg --install ${file}; then
    _log "Installing other dependencies ..."
    ag_install fix-broken
    omvextrasInstall=$(dpkg -l | awk '$2 == "openmediavault-omvextrasorg" { print $1 }')
    if [[ ! "${omvextrasInstall}" == "ii" ]]; then
      _log "omv-extras failed to install correctly.  Trying to fix apt ..."
      if ! ag_install fix-broken; then
        _log "Fix failed and openmediavault-omvextrasorg is in a bad state."
        exit 3
      fi
    fi
    omvextrasInstall=$(dpkg -l | awk '$2 == "openmediavault-omvextrasorg" { print $1 }')
    if [[ ! "${omvextrasInstall}" == "ii" ]]; then
      _log "openmediavault-omvextrasorg package failed to install or is in a bad state."
      exit 3
    fi
  fi

  _log "Updating repos ..."
  ${aptclean} repos
else
  _log "There was a problem downloading the package."
fi

# disable armbian log services if found
for service in log2ram armbian-ramlog armbian-zram-config; do
  if systemctl list-units --full -all | grep ${service}; then
    systemctl stop ${service}
    systemctl disable ${service}
  fi
done
rm -f /etc/cron.daily/armbian-ram-logging
if [ -f "/etc/default/armbian-ramlog" ]; then
  sed -i "s/ENABLED=.*/ENABLED=false/g" /etc/default/armbian-ramlog
fi
if [ -f "/etc/default/armbian-zram-config" ]; then
  sed -i "s/ENABLED=.*/ENABLED=false/g" /etc/default/armbian-zram-config
fi
if [ -f "/etc/systemd/system/logrotate.service" ]; then
  rm -f /etc/systemd/system/logrotate.service
  systemctl daemon-reload
fi

# install flashmemory/writecache plugin unless disabled
if [ ${skipFlash} -eq 1 ]; then
  _log "Skipping installation of the ${flash} plugin."
else
  if [ "${flash}" = "flashmemory" ]; then
    _log "Install folder2ram..."
    if ! ag_install normal folder2ram; then
      _log "Installed folder2ram."
    else
      _log "Failed to install folder2ram."
    fi
  fi
  _log "Install ${flash} plugin..."
  if ! ag_install normal openmediavault-${flash}; then
    _log "Installed ${flash} plugin."
  else
    _log "Failed to install ${flash} plugin."
    omv-salt deploy run ${flash}
    ag_install fix-broken
  fi
  if [ ! "${flash}" = "flashmemory" ]; then
    omv_config_update "/config/services/writecache/enable" "1"
  fi
fi

# change default OMV settings
if [ -n "${smbOptions}" ]; then
  omv_config_update "/config/services/smb/extraoptions" "$(echo -e "${smbOptions}")"
fi
omv_config_update "/config/services/ssh/enable" "1"
omv_config_update "/config/services/ssh/permitrootlogin" "1"
omv_config_update "/config/system/time/ntp/enable" "1"
omv_config_update "/config/system/time/timezone" "${tz}"
omv_config_update "/config/system/network/dns/hostname" "${hostname}"
if [ -n "${domainname}" ]; then
  omv_config_update "/config/system/network/dns/domainname" "${domainname}"
fi

# disable monitoring and apply changes
_log "Disabling data collection ..."
/usr/sbin/omv-rpc -u admin "perfstats" "set" '{"enable":false}'
/usr/sbin/omv-rpc -u admin "config" "applyChanges" '{ "modules": ["monit","rrdcached","collectd"],"force": true }'

# set min/max frequency and watchdog for RPi boards
rpi_model="/proc/device-tree/model"
if [ -f "${rpi_model}" ] && [[ $(awk '{ print $1 }' ${rpi_model}) = "Raspberry" ]]; then
  if [ ${version} -lt 6 ]; then
    omv_set_default "OMV_WATCHDOG_DEFAULT_MODULE" "bcm2835_wdt"
    omv_set_default "OMV_WATCHDOG_CONF_WATCHDOG_TIMEOUT" "14"
  fi
  omv_set_default "OMV_WATCHDOG_SYSTEMD_RUNTIMEWATCHDOGSEC" "14s" true

  MIN_SPEED="$(</sys/devices/system/cpu/cpufreq/policy0/cpuinfo_min_freq)"
  MAX_SPEED="$(</sys/devices/system/cpu/cpufreq/policy0/cpuinfo_max_freq)"
  # Determine if RPi4 (for future use)
  if [[ $(awk '$1 == "Revision" { print $3 }' /proc/cpuinfo) =~ [a-c]03111 ]]; then
    BOARD="rpi4"
  fi
  cat << EOF > ${cpuFreqDef}
GOVERNOR="schedutil"
MIN_SPEED="${MIN_SPEED}"
MAX_SPEED="${MAX_SPEED}"
EOF
fi

# get default governor for kernel
modprobe --quiet configs
if [ -f "/proc/config.gz" ]; then
  defaultGov="$(zgrep "${defaultGovSearch}" /proc/config.gz | sed -e "s/${defaultGovSearch}\(.*\)=y/\1/")"
elif [ -f "/boot/config-$(uname -r)" ]; then
  defaultGov="$(grep "${defaultGovSearch}" /boot/config-$(uname -r) | sed -e "s/${defaultGovSearch}\(.*\)=y/\1/")"
fi

# governor and speed variables
if [ ${armbian} -eq 1 ]; then
  if [ -n "${defaultGov}" ]; then
    GOVERNOR="${defaultGov,,}"
  elif [ -n "${gov}" ]; then
    GOVERNOR="${gov}"
  fi
  if [ -n "${minspd}" ]; then
    MIN_SPEED="${minspd}"
  fi
  if [ -n "${maxspd}" ]; then
    MAX_SPEED="${maxspd}"
  fi
elif [ -f "${cpuFreqDef}" ]; then
  . ${cpuFreqDef}
else
  if [ -z "${DEFAULT_GOV}" ]; then
    defaultGov="ondemand"
  fi
  GOVERNOR=${defaultGov,,}
  MIN_SPEED="0"
  MAX_SPEED="0"
fi

# set defaults in /etc/default/openmediavault
# set defaults in /etc/default/openmediavault
if [ ${version} -ge 8 ]; then
  omv_set_default "OMV_CPUPOWER_GOVERNOR" "${GOVERNOR}"
  omv_set_default "OMV_CPUPOWER_MINSPEED" "${MIN_SPEED}"
  omv_set_default "OMV_CPUPOWER_MAXSPEED" "${MAX_SPEED}"
else
  omv_set_default "OMV_CPUFREQUTILS_GOVERNOR" "${GOVERNOR}"
  omv_set_default "OMV_CPUFREQUTILS_MINSPEED" "${MIN_SPEED}"
  omv_set_default "OMV_CPUFREQUTILS_MAXSPEED" "${MAX_SPEED}"
fi

# update pillar default list - /srv/pillar/omv/default.sls
omv-salt stage run prepare

# update config files
omv-salt deploy run nginx phpfpm samba ${flash} ssh chrony timezone monit rrdcached collectd ${cpuState} apt watchdog

# restart engined
systemctl restart openmediavault-engined

# create php directories if they don't exist
modDir="/var/lib/php/modules"
if [ ! -d "${modDir}" ]; then
  mkdir --parents --mode=0755 ${modDir}
fi
sessDir="/var/lib/php/sessions"
if [ ! -d "${sessDir}" ]; then
  mkdir --parents --mode=1733 ${sessDir}
fi

if [ -f "${forceIpv4}" ]; then
  rm ${forceIpv4}
fi

if [ -f "/etc/init.d/proftpd" ]; then
  systemctl disable proftpd.service
  systemctl stop proftpd.service
fi

# add admin user to openmediavault-admin group if it exists
if getent passwd admin > /dev/null; then
  usermod -a -G openmediavault-admin admin
fi

if [[ "${arch}" == "amd64" ]] || [[ "${arch}" == "i386" ]]; then
  # skip ionice on x86 boards
  _log "Done."
  exit 0
fi

if [ ! "${GOVERNOR,,}" = "schedutil" ]; then
  _log "Add a cron job to make NAS processes more snappy and silence rsyslog"
  cat << EOF > /etc/rsyslog.d/omv-armbian.conf
:msg, contains, "omv-ionice" ~
:msg, contains, "action " ~
:msg, contains, "netsnmp_assert" ~
:msg, contains, "Failed to initiate sched scan" ~
EOF
  systemctl restart rsyslog

  # add taskset to ionice cronjob for biglittle boards
  case ${BOARD} in
    odroidxu4|bananapim3|nanopifire3|nanopct3plus|nanopim3|nanopi-r6s)
      taskset='; taskset -c -p 4-7 ${srv}'
      ;;
    *rk3399*|*edge*|nanopct4|nanopim4|nanopineo4|renegade-elite|rockpi-4*|rockpro64|helios64)
      taskset='; taskset -c -p 4-5 ${srv}'
      ;;
    odroidn2)
      taskset='; taskset -c -p 2-5 ${srv}'
      ;;
  esac

  # create ionice script
  cat << EOF > ${ioniceScript}
#!/bin/sh

for srv in \$(pgrep "ftpd|nfsiod|smbd"); do
  ionice -c1 -p \${srv} ${taskset};
done
EOF
  chmod 755 ${ioniceScript}

  # create ionice cronjob
  cat << EOF > ${ioniceCron}
* * * * * root ${ioniceScript} >/dev/null 2>&1
EOF
  chmod 600 ${ioniceCron}
fi

# add pi user to ssh group if it exists
if getent passwd pi > /dev/null; then
  _log "Adding pi user to ssh group ..."
  usermod -a -G _ssh pi
fi

# add user running the script to ssh group if not pi or root
if [ -n "${SUDO_USER}" ] && [ ! "${SUDO_USER}" = "root" ] && [ ! "${SUDO_USER}" = "pi" ]; then
  if getent passwd ${SUDO_USER} > /dev/null; then
    _log "Adding ${SUDO_USER} to the _ssh group ..."
    usermod -a -G _ssh ${SUDO_USER}
  fi
fi

# remove networkmanager and dhcpcd5 then configure networkd
if [ ${skipNet} -ne 1 ]; then

  if [ "${BOARD}" = "helios64" ]; then
    echo -e '#!/bin/sh\n/usr/sbin/ethtool --offload eth1 rx off tx off' > /usr/lib/networkd-dispatcher/routable.d/10-disable-offloading
  fi

  defLink="/etc/systemd/network/99-default.link"
  rm -fv "${defLink}"
  if [ ${rpi} -eq 1 ] && [ ${version} -eq 7 ]; then
    _log "Force eth0 name on RPi ..."
    mac="$(ip -j a show dev eth0 | jq -r .[].address | head -n1)"
    if [ -z "${mac}" ]; then
      mac="$(ip -j a show dev end0 | jq -r .[].address | head -n1)"
    fi
    _log "mac address - ${mac}"
    if [ -n "${mac}" ]; then
      echo -e "[Match]\nMACAddress=${mac}\n[Link]\nName=eth0" > /etc/systemd/network/10-persistent-eth0.link
    fi
  fi

  if systemctl is-active --quiet network-manager 2>/dev/null; then
    nm=1
  fi

  _log "Enable and start systemd-resolved ..."
  systemctl enable systemd-resolved
  systemctl start systemd-resolved
  rm /etc/resolv.conf
  ln -s /run/systemd/resolve/resolv.conf /etc/resolv.conf

  if [ -f "${rfkill}" ]; then
    _log "Unblocking wifi with rfkill ..."
    ${rfkill} unblock all
  fi

  for nic in $(ls /sys/class/net | grep -vE "br-|docker|dummy|ip6|lo|sit|tun|veth|virbr|wg"); do
    if [ ${nm} -eq 1 ]; then
      nmcli device set "${nic}" managed no || true
    fi
    if grep -q "<devicename>${nic}</devicename>" ${OMV_CONFIG_FILE}; then
      _log "${nic} already found in database.  Skipping..."
      continue
    fi
    if udevadm info /sys/class/net/${nic} | grep -q wlan; then
      if [ -f "${wpaConf}" ]; then
        country=$(awk -F'=' '/country=/{gsub(/["\r]/,""); print $NF}' ${wpaConf})
        wifiName=$(awk -F'=' '/ssid="/{st=index($0,"="); ssid=substr($0,st+1); gsub(/["\r]/,"",ssid); print ssid; exit}' ${wpaConf})
        wifiPass=$(awk -F'=' '/psk="/{st=index($0,"="); pass=substr($0,st+1); gsub(/["\r]/,"",pass); print pass; exit}' ${wpaConf})

        if [ -n "${country}" ] && [ -n "${wifiName}" ] && [ -n "${wifiPass}" ]; then
          if [ -f "${crda}" ]; then
            awk -i inplace -F'=' -v country="$country" '/REGDOMAIN=/{$0=$1"="country} {print $0}' ${crda}
          fi
          _log "Adding ${nic} to openmedivault database ..."
          jq --null-input --compact-output \
            "{uuid: \"${OMV_CONFIGOBJECT_NEW_UUID}\", devicename: \"${nic}\", type: \"wifi\", method: \"dhcp\", method6: \"dhcp\", wpassid: \"${wifiName}\", wpapsk: \"${wifiPass}\"}" | \
            omv-confdbadm update "conf.system.network.interface" -
          if grep -q "<devicename>${nic}</devicename>" ${OMV_CONFIG_FILE}; then
            cfg=1
          fi
        fi
      fi
    else
      _log "Adding ${nic} to openmedivault database ..."
      if [ -n "$(ip -j -o -4 addr show ${nic} | jq --raw-output  '.[] | select(.addr_info[0].dev) | .addr_info[0].local')" ] && \
      [ "$(ip -j -o -4 addr show ${nic} | jq --raw-output '.[] | select(.addr_info[0].dev) | .addr_info[0].dynamic')" == "null" ]; then
        ipv4Addr=$(ip -j -o -4 addr show ${nic} | jq --raw-output '.[] | select(.addr_info[0].dev) | .addr_info[0].local')
        ipv4CIDR=$(ip -j -o -4 addr show ${nic} | jq --raw-output '.[] | select(.addr_info[0].dev) | .addr_info[0].prefixlen')
        bitmaskValue=$(( 0xffffffff ^ ((1 << (32 - ipv4CIDR)) - 1) ))
        ipv4Netmask=$(( (bitmaskValue >> 24) & 0xff )).$(( (bitmaskValue >> 16) & 0xff )).$(( (bitmaskValue >> 8) & 0xff )).$(( bitmaskValue & 0xff ))
        ipv4GW=$(ip -j -o -4 route show | jq --raw-output '.[] | select(.dst=="default") | .gateway')
        jq --null-input --compact-output \
        "{uuid: \"${OMV_CONFIGOBJECT_NEW_UUID}\", devicename: \"${nic}\", method: \"static\", address: \"${ipv4Addr}\", netmask: \"${ipv4Netmask}\", gateway: \"${ipv4GW}\", dnsnameservers: \"8.8.8.8 ${ipv4GW}\"}" | \
        omv-confdbadm update "conf.system.network.interface" -
      else
        jq --null-input --compact-output \
        "{uuid: \"${OMV_CONFIGOBJECT_NEW_UUID}\", devicename: \"${nic}\", method: \"dhcp\", method6: \"dhcp\"}" | \
        omv-confdbadm update "conf.system.network.interface" -
      fi

      if grep -q "<devicename>${nic}</devicename>" ${OMV_CONFIG_FILE}; then
        cfg=1
      fi
    fi
  done

  _log "Removing old NetworkManager netplan files..."
  grep -l NetworkManager /etc/netplan/* 2>/dev/null | xargs -r rm -fv

  if [ ${nm} -eq 1 ]; then
    _log "Disable NetworkManager start on boot ..."
    systemctl disable NetworkManager
  fi

  nm_pkgs=(network-manager dhcpcd5 cloud-init)
  if [ ${cfg} -eq 1 ]; then
    _log "IP address may change and you could lose connection if running this script via ssh."

    # create config files
    omv-salt deploy run systemd-networkd
    if [ ${PIPESTATUS[0]} -gt 0 ]; then
      _log "Error applying network changes.  Skipping reboot!"
      skipReboot=1
    fi

    _log "Removing network-manager and dhcpcd5 ..."
    ag_install purge "${nm_pkgs[@]}"

    if [ ${skipReboot} -ne 1 ]; then
      _log "Network setup.  Rebooting..."
      reboot
    fi
  else
    _log "Removing network-manager and dhcpcd5 ..."
    ag_install purge "${nm_pkgs[@]}"

    _log "It is recommended to reboot and then setup the network adapter in the openmediavault web interface."
  fi

fi

_log "done."

exit 0
