#!/usr/bin/env bash
# author: joe.zheng
# version: 24.04.02

set -e

# @self {
# AUTO-GENERATED, DO NOT EDIT!

SELF="$(basename $0)"
SELF_VERSION="$(sed -n '1,4s/# version: \(.*\)/\1/p' $0)"

# @self }
NAME="${SELF#*-}"

VERSION="0.14.3"      # version to deploy
CUR_VER=              # current version if any
RESET=n               # reset the deployment
UNINSTALL=n           # reset the deployment and uninstall components

REPO_URL="https://github.com/kubernetes-sigs/node-feature-discovery"

TIMEOUT="300s"
NAMESPACE="node-feature-discovery"

# @dry-run {
# AUTO-GENERATED, DO NOT EDIT!

DRY_RUN="${DRY_RUN:-n}"        # "y" to enable
RUN=''                         # command prefix for dry run
if [[ $DRY_RUN == 'y' ]]; then
  RUN='echo'
fi

# @dry-run }

function usage() {
  cat <<EOF
Usage: $SELF [-m <type>] [-v <ver>] [-R] [-U] [-n] [-h]

  Deploy NFD in Kubernetes cluster the easy way

  -m <type>: use mirror [$MIRRORS], default: $MIRROR
  -v <ver>:  target version, default: $VERSION
  -R:        reset the deployment, default: $RESET
  -U:        reset the deployment and uninstall components, default: $UNINSTALL
  -n:        print information only, default: $DRY_RUN
  -h:        print the usage message

Cache:

  To speed up deployment, the required files will be cached at "$CACHE"

Environment variables:

  MIRROR_URL:  mirror to use, default: $MIRROR_URL
  OFFLINE:     force into offline mode [y n], default: $OFFLINE

Examples:

  1. Deploy NFD
     $SELF

  2. Reset the deployment
     $SELF -R

  3. Deploy NFD with specific version
     $SELF -v $VERSION

  4. Reset the deployment and uninstall
     $SELF -U

Version: $SELF_VERSION
EOF

}

function current_version() {
  local n="nfd-master"
  local version=
  local current="$(kubectl exec -n $NAMESPACE deploy/$n -- $n -version 2>/dev/null | sed -n "s/^$n\s*v\(.*\)/\1/p")"
  if [[ -n "$current" ]]; then
    version="$current"
  fi
  echo $version
}

function main() {
  # adjust default version if already deployed
  CUR_VER="$(current_version)"
  VERSION="${CUR_VER:-$VERSION}"

  while getopts ":m:v:hnRU" opt
  do
    case $opt in
      m ) MIRROR=$OPTARG
          if echo $MIRRORS | grep -v -w $MIRROR >/dev/null 2>&1; then
            err "invalid mirror option $MIRROR"
            usage && exit 1
          fi
          ;;
      v ) VERSION=${OPTARG#v};;
      R ) RESET=y;;
      U ) RESET=y && UNINSTALL=y;;
      n ) DRY_RUN=y && RUN='echo';;
      h ) usage && exit;;
      * ) usage && echo "invalid option: -$OPTARG" && exit 1;;
    esac
  done
  shift $((OPTIND-1))

  for v in CACHE DRY_RUN MIRROR MIRROR_URL OFFLINE RESET UNINSTALL VERSION CUR_VER
  do
    eval echo "$v: \${$v}"
  done

  [[ $DRY_RUN == "y" ]] && exit

  check_prerequisites
  check_network
  check_mirror
  ensure_workdir

  local dir_deploy="deployment"
  local manifest_dir="$CACHE_MANIFESTS/$NAME-$VERSION"
  local manifest_dir_deploy="$manifest_dir/$dir_deploy"
  local package_dir="$CACHE_PACKAGES/common/$NAME-$VERSION"
  local package_file="v$VERSION.tar.gz"
  local package_path="$package_dir/$package_file"

  mkdir -p $package_dir $manifest_dir

  msg "download package"
  if [[ $OFFLINE == "y" ]]; then
    msg "WARNING: offline mode, cache must be ready"
  else
    local url="$REPO_URL/archive/refs/tags/$package_file"
    download_file "$(mirror_url $url)" "$package_path"
  fi

  msg "prepare manifest"
  if [[ ! -d "$manifest_dir_deploy" ]]; then
    msg "extract $package_path -> $manifest_dir_deploy"
    tar xzf $package_path -C $manifest_dir --strip-components=1 --no-wildcards-match-slash --wildcards "*/$dir_deploy/"
  fi

  if [[ $RESET == "y" ]]; then
    msg "delete $NAME deployment (if any)"
    kubectl delete --ignore-not-found -k "$manifest_dir_deploy/overlays/default"
    if [[ -n "$CUR_VER" ]]; then
      msg "remove $NAME-related node labels"
      local prune="$manifest_dir_deploy/overlays/prune"
      kubectl apply -k "$prune"
      kubectl -n $NAMESPACE wait job/nfd-master --for=condition=complete \
        && kubectl delete -k "$prune"
    fi
  else
    msg "deploy $NAME"
    for m in default topologyupdater; do
      kubectl apply -k "$manifest_dir_deploy/overlays/$m"
    done
  fi

  if [[ $RESET != "y" ]]; then
    msg "wait until ready (timeout: $TIMEOUT)"
    kubectl -n $NAMESPACE wait deploy/nfd-master --timeout $TIMEOUT --for condition=Available

    cat <<EOF

# here are some tips to follow:
# check current status
kubectl get all -n $NAMESPACE

# check labels and annotations of the nodes
kubectl describe node | less

# check more details from $REPO_URL
EOF
  fi

  msg "done"
}

function check_prerequisites() {
  msg "check prerequisites"
  if [[ -z $(which kubelet) ]]; then
    err "kubelet is not available"
    exit 1
  fi
  if [[ -z $(which curl) ]]; then
    err "curl is not available"
    exit 1
  fi
  if ! kubectl version >/dev/null 2>&1; then
    err "can't access k8s cluster"
    exit 1
  fi
}

# @base {
# AUTO-GENERATED, DO NOT EDIT!

function msg {
  echo "> $@"
}

function err {
  echo "> $@" >&2
}

function has() {
  [[ -z "${1##*$2*}" ]] && [[ -z "$2" || -n "$1" ]]
}

# @base }

# @sudo {
# AUTO-GENERATED, DO NOT EDIT!

SUDO="sudo"
if [[ $(id -u) == "0" ]]; then
  SUDO=""
fi

function validate_sudo() {
  if [[ -n $SUDO ]]; then
    msg "validate sudo"
    sudo -v
  fi
}

# @sudo }

# @network {
# AUTO-GENERATED, DO NOT EDIT!

OFFLINE="${OFFLINE:-n}"                           # no external network
MIRROR="${MIRROR:-auto}"                          # mirror option to use
MIRRORS="yes no auto"                             # valid mirror options
USE_MIRROR="${USE_MIRROR:-n}"                     # need to use mirror
MIRROR_URL="${MIRROR_URL:-https://iffi.me/proxy}" # mirror or http proxy to use
URL_TO_CHECK="${URL_TO_CHECK:-https://raw.githubusercontent.com}"

# the target URL is reachable but the response may be 4xx or 5xx
function can_access() {
   curl -IL -s -m 5 $1 >/dev/null 2>&1
}

function check_network() {
  msg "check network"
  if [[ $OFFLINE != 'y' ]]; then
    if ! can_access example.com; then
      msg "can't access external network"
      OFFLINE="y"
    fi
  fi
  msg "offline mode: $OFFLINE"
}

function check_mirror() {
  msg "use mirror or not"

  local mirror;
  if [[ $MIRROR == "auto" ]]; then
    mirror="yes" # default as needed
    if [[ $OFFLINE == "y" ]]; then
      msg "offline mode, assume mirror is needed"
    else
      local target="$URL_TO_CHECK"
      msg "check whether we can access $target"
      if can_access $target; then
        msg "curl $target is OK"
        mirror="no"
      else
        msg "curl $target is FAILED"
      fi
    fi
  fi
  if [[ $MIRROR == "yes" || $mirror == "yes" ]]; then
    msg "mirror is needed"
    if can_access $MIRROR_URL; then
      USE_MIRROR="y"
    else
      err "failed to access mirror ($MIRROR_URL)"
    fi
  fi
  msg "use mirror: $USE_MIRROR"
}

function mirror_url() {
  local origin="${1:?argument missing}"

  if [[ $USE_MIRROR == "y" ]]; then
    echo -n "$MIRROR_URL/$origin"
  else
    echo -n "$origin"
  fi
}

# @network }

# @cache {
# AUTO-GENERATED, DO NOT EDIT!

CACHE="${CACHE:-cache}"                                    # the cache directory
CACHE_RUN="${CACHE_RUN:-$CACHE/run/$SELF}"                 # runtime generated files
CACHE_IMAGES="${CACHE_IMAGES:-$CACHE/images}"              # exported container images
CACHE_PACKAGES="${CACHE_PACKAGES:-$CACHE/packages}"        # software packages, e.g. .deb, .tar.gz
CACHE_MANIFESTS="${CACHE_MANIFESTS:-$CACHE/manifests}"     # manifest files in YAML format
CACHE_DOWNLOADING="${CACHE_DOWNLOADING:-$CACHE/.download}" # temporary directory for downloading

function ensure_workdir() {
  msg "ensure workdir"

  for d in $CACHE_RUN $CACHE_IMAGES $CACHE_PACKAGES $CACHE_MANIFESTS $CACHE_DOWNLOADING; do
    if [[ ! -d $d ]]; then
      msg "create dir: $d"
      mkdir -p $d
    fi
  done
}

function download_file() {
  local src="${1:?missing source url}"
  local dst="${2:?missing destination}"

  if [[ -f "$dst" ]]; then
    msg "already exist: $dst"
  else
    msg "download: $src"
    local tmp="$CACHE_DOWNLOADING/$(basename $dst)"
    $RUN curl -fsSL $src > $tmp
    $RUN mkdir -p $(dirname $dst) && mv $tmp $dst
    msg "saved at: $dst"
  fi
}

# @cache }

main "$@"
