#!/bin/bash

set -e
set -u

FORCE=${FORCE:-false}
SIMULATE=${SIMULATE:-false}

error() {
  echo "ERROR: $*" >&2
}

die() {
  error "$*"
  exit 1
}

usage() {
  echo "usage: $0 [-f|-s]"
}

while getopts fs shortopt
do
  case "$shortopt" in
    f) FORCE=true ;;
    s) SIMULATE=true ;;
    ?) usage; exit 0;;
  esac
done
shift $((OPTIND - 1))

if ${FORCE} && ${SIMULATE} ; then
  error "Cannot have FORCE and SIMULATE enabled at the same time"
  usage >&2
  exit 1
fi

if [[ $# -ne 0 ]] ; then
  error "$# arguments received, 0 expected"
  usage >&2
  exit 1
fi

FILE=/etc/udev/rules.d/70-persistent-net.rules

echo "INFO: Running $0 to generate file '${FILE}'"

if [[ -r "${FILE}" ]]; then
  echo "INFO: The file '${FILE}' already exists, the content is:"
  echo "----------------------------------------"
  cat "${FILE}"
  echo "----------------------------------------"
  if ${FORCE} ; then
    echo "WARNING: FORCE enabled, will overwrite the file"
  elif ${SIMULATE} ; then
    echo "INFO: SIMULATE enabled, will continue show what will be written"
  else
    echo "INFO: file exists and will not overwrite because FORCE is disabled (use '-f' to enable)"
    exit 0
  fi
fi

pciid_list_raw=()
for dev_path in /sys/class/net/*e*[0-9]*; do
  dev="${dev_path//*\//}"
  pciid=$(ethtool -i "${dev}" | awk '/^bus-info: / {print $2}' || echo "none")
  if [[ "${pciid}" = "none" ]]; then
    echo "INFO: Detecting device '${dev}' with no PCIID, skipping"
    continue
  else
    echo "INFO: Detecting device '${dev}' with PCIID '${pciid}'"
  fi
  pciid_list_raw+=("${pciid}")
done

readarray -t pciid_list < <(printf '%s\n' "${pciid_list_raw[@]}" | sort)

FILE_TMP=$(mktemp -t ngcp-init-udev-XXXXXXXXXX)

cat >"${FILE_TMP}" <<EOF
# Generated by Sipwise script $0
EOF

max_dev=$((${#pciid_list[@]} - 1))
for i in $(seq 0 ${max_dev}); do
  dev="neth$i"
  pciid="${pciid_list[$i]}"
  echo "INFO: Adding device '${dev}' with PCIID '${pciid}' to file"

  cat >>"${FILE_TMP}" <<EOF
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", KERNELS=="${pciid}", NAME="${dev}"
EOF
done

echo "INFO: Contents of new file after generating it:"
echo "----------------------------------------"
cat "${FILE_TMP}"
echo "----------------------------------------"

if ${SIMULATE} ; then
  echo "INFO: SIMULATE enabled, stop before writing to '${FILE}'"
  rm -rf "${FILE_TMP}"
  exit 0
fi

echo "INFO: Creating or replacing '${FILE}' with newly generated content"
rm -vf "${FILE}"
mv -v "${FILE_TMP}" "${FILE}"
chown root:root "${FILE}"
chmod 0644 "${FILE}"
