#!/usr/bin/env bash
set -euo pipefail

host_root="/host"
env_file="${host_root}/etc/systemd/system/k3s.service.env"
manifest_dir="${host_root}/var/lib/rancher/k3s/server/manifests"

changed=0

ensure_disable_flag() {
  mkdir -p "$(dirname "${env_file}")"
  if [ ! -f "${env_file}" ]; then
    printf 'K3S_DISABLE=traefik\n' > "${env_file}"
    changed=1
    return
  fi

  if grep -q '^K3S_DISABLE=' "${env_file}"; then
    current="$(grep '^K3S_DISABLE=' "${env_file}" | tail -n1 | cut -d= -f2-)"
    current="$(printf '%s' "${current}" | sed 's/^\"//;s/\"$//' | tr -d ' ')"
    if ! printf '%s' "${current}" | grep -qw "traefik"; then
      if [ -z "${current}" ]; then
        updated="traefik"
      else
        updated="${current},traefik"
      fi
      sed -i "s/^K3S_DISABLE=.*/K3S_DISABLE=${updated}/" "${env_file}"
      changed=1
    fi
  else
    printf '\nK3S_DISABLE=traefik\n' >> "${env_file}"
    changed=1
  fi
}

remove_manifest() {
  if [ -d "${manifest_dir}" ] && ls "${manifest_dir}"/traefik* >/dev/null 2>&1; then
    rm -f "${manifest_dir}"/traefik*.yaml "${manifest_dir}"/traefik*.yml
    changed=1
  fi
}

restart_k3s() {
  node_name="$(cat "${host_root}/etc/hostname" 2>/dev/null || hostname)"
  delay=0
  case "${node_name}" in
    *0b) delay=60 ;;
    *0c) delay=120 ;;
  esac
  if [ "${delay}" -gt 0 ]; then
    sleep "${delay}"
  fi
  chroot "${host_root}" /bin/systemctl daemon-reload || true
  chroot "${host_root}" /bin/systemctl restart k3s
}

cleanup_cluster_objects() {
  kubectl -n kube-system delete addon traefik --ignore-not-found --wait=false >/dev/null 2>&1 || true
  kubectl -n kube-system delete helmchart traefik traefik-crd --ignore-not-found --wait=false >/dev/null 2>&1 || true
  kubectl -n kube-system delete job helm-install-traefik helm-install-traefik-crd --ignore-not-found --wait=false >/dev/null 2>&1 || true
  kubectl -n kube-system delete deployment traefik --ignore-not-found --wait=false >/dev/null 2>&1 || true
  kubectl -n kube-system delete service traefik --ignore-not-found --wait=false >/dev/null 2>&1 || true
  kubectl -n kube-system delete serviceaccount traefik helm-traefik helm-traefik-crd --ignore-not-found --wait=false >/dev/null 2>&1 || true
  kubectl delete clusterrole traefik-ingress-controller traefik-kube-system --ignore-not-found --wait=false >/dev/null 2>&1 || true
  kubectl delete clusterrolebinding helm-kube-system-traefik helm-kube-system-traefik-crd traefik-ingress-controller traefik-kube-system --ignore-not-found --wait=false >/dev/null 2>&1 || true
}

while true; do
  changed=0
  ensure_disable_flag
  remove_manifest

  if [ "${changed}" -eq 1 ]; then
    restart_k3s
    sleep 15
    remove_manifest
  fi

  cleanup_cluster_objects
  sleep 300
done
