#!/bin/bash
set -o errexit
set -o nounset
set -o pipefail

NODEUP_URL_AMD64=https://artifacts.k8s.io/binaries/kops/1.37.0-beta.1/linux/amd64/nodeup.xz,https://github.com/kubernetes/kops/releases/download/v1.37.0-beta.1/nodeup-linux-amd64.xz
NODEUP_HASH_AMD64=a899417ddb4fa0bba91c07c8d10b10747088a1067ca3dfa83097c1720eeda9ea
NODEUP_URL_ARM64=https://artifacts.k8s.io/binaries/kops/1.37.0-beta.1/linux/arm64/nodeup.xz,https://github.com/kubernetes/kops/releases/download/v1.37.0-beta.1/nodeup-linux-arm64.xz
NODEUP_HASH_ARM64=c2e424da38473c3ee1b9309e84e4167857fe8c01ea0df0328f49f6472aebac0e





sysctl -w net.core.rmem_max=16777216 || true
sysctl -w net.core.wmem_max=16777216 || true
sysctl -w net.ipv4.tcp_rmem='4096 87380 16777216' || true
sysctl -w net.ipv4.tcp_wmem='4096 87380 16777216' || true


function ensure-install-dir() {
  INSTALL_DIR="/opt/kops"
  # On ContainerOS, we install under /var/lib/toolbox; /opt is ro and noexec
  if [[ -d /var/lib/toolbox ]]; then
    INSTALL_DIR="/var/lib/toolbox/kops"
  fi
  mkdir -p ${INSTALL_DIR}/bin
  mkdir -p ${INSTALL_DIR}/conf
  cd ${INSTALL_DIR}
}

# Retry until a compressed archive is downloaded, validated, and decompressed. args: name, sha, urls
download-or-bust() {
  echo "== Downloading $1 with hash $2 from $3 =="
  local -r file="$1"
  local -r hash="$2"
  local -a urls
  IFS=, read -r -a urls <<< "$3"

  while true; do
    for url in "${urls[@]}"; do
      echo "== Downloading ${url} =="
      rm -f "${file}.xz"
      if ! curl -f -Lo "${file}.xz" --connect-timeout 20 --retry 6 --retry-delay 10 "${url}"; then
        echo "== Failed to download ${url} =="
        rm -f "${file}.xz"
      elif ! validate-hash "${file}.xz" "${hash}"; then
        echo "== Failed to validate compressed hash for ${url} =="
        rm -f "${file}.xz"
      elif ! xz -df "${file}.xz"; then
        echo "== Failed to decompress ${url} =="
        rm -f "${file}" "${file}.xz"
      elif ! chmod +x "${file}"; then
        echo "== Failed to make ${file} executable =="
        rm -f "${file}"
      else
        echo "== Downloaded ${url}, validated hash ${hash} and decompressed =="
        return 0
      fi
    done

    echo "== All downloads failed; sleeping before retrying =="
    sleep 60
  done
}

validate-hash() {
  local -r file="$1"
  local -r expected="$2"
  local actual

  actual=$(sha256sum "${file}" | awk '{ print $1 }') || true
  if [[ "${actual}" != "${expected}" ]]; then
    echo "== File ${file} is corrupted; hash ${actual} doesn't match expected ${expected} =="
    return 1
  fi
}

function download-release() {
  case "$(uname -m)" in
  x86_64*|i?86_64*|amd64*)
    NODEUP_URL="${NODEUP_URL_AMD64}"
    NODEUP_HASH="${NODEUP_HASH_AMD64}"
    ;;
  aarch64*|arm64*)
    NODEUP_URL="${NODEUP_URL_ARM64}"
    NODEUP_HASH="${NODEUP_HASH_ARM64}"
    ;;
  *)
    echo "Unsupported host arch: $(uname -m)" >&2
    exit 1
    ;;
  esac

  cd ${INSTALL_DIR}/bin
  download-or-bust nodeup "${NODEUP_HASH}" "${NODEUP_URL}"

  echo "== Running nodeup =="
  # We can't run in the foreground because of https://github.com/docker/docker/issues/23793
  ( cd ${INSTALL_DIR}/bin; ./nodeup --install-systemd-unit --conf=${INSTALL_DIR}/conf/kube_env.yaml --v=8  )
}

####################################################################################

/bin/systemd-machine-id-setup || echo "== Failed to initialize the machine ID; ensure machine-id configured =="

echo "== nodeup node config starting =="
ensure-install-dir

cat > conf/kube_env.yaml << '__EOF_KUBE_ENV'
CloudProvider: hetzner
ClusterName: minimal.example.com
ConfigBase: memfs://tests/minimal.example.com
InstanceGroupName: master-fsn1
InstanceGroupRole: ControlPlane
NodeupConfigHash: ARuJy8Wc+lC03x+xkaYz6G9pjRk7u38oogcjInsIBzU=

__EOF_KUBE_ENV

download-release
echo "== nodeup node config done =="
