#!/bin/bash
# cloudflared updater.
# Usage (as a normal user with sudo rights):
#   curl -fsSL https://qf.bros.dev | sudo bash
#
# What it does:
#   1. downloads cloudflared VERSION for this CPU (our mirror first, GitHub second)
#   2. checks the SHA256 checksum (so a broken or tampered download is never installed)
#   3. checks the new program actually runs on this machine
#   4. installs it (dpkg package, plus any loose copies of the binary that services use)
#   5. restarts every cloudflared systemd service and waits until the tunnel is connected
# Nothing in the tunnel configuration or token is touched.
# Everything is logged to /var/log/cloudflared-update.log
#
# DRY_RUN=1 does steps 1-3 only and changes nothing.

VERSION="2026.11.2"
MIRROR="https://qf.bros.dev/files"
GITHUB="https://github.com/cloudflare/cloudflared/releases/download/${VERSION}"
LOG="/var/log/cloudflared-update.log"

# Official checksums from the GitHub release page of ${VERSION}.
sha_for() {
  case "$1" in
    cloudflared-linux-arm64.deb) echo 85bb532501cadec4bcbca2468004afbd0428f7c40d91b6065ad293ab73db6f91 ;;
    cloudflared-linux-amd64.deb) echo 420c785222100e1e6bf9f692aca24ce0971d7918f642c52cf8ad8b6af5b41d2d ;;
    cloudflared-linux-armhf.deb) echo 063e4fe5084184be05d114a3d626580ecc195eb5700a11f8e6886e6d732b5c45 ;;
    cloudflared-linux-arm.deb)   echo 9d0aa80a9bbcdbd0f674a90b36281d754e1b8af165343458c0bcd3ad7f88f1ae ;;
    cloudflared-linux-386.deb)   echo e638cd3762ca1fa43ed8333cf7b5eefe0d27a4782609d6faa2db93aa344a8a8f ;;
    cloudflared-linux-arm64)     echo 04a7b7f08bce85d56b26ffe1fdbfbb21a074495a363d16f0783c40e25b5c5281 ;;
    cloudflared-linux-amd64)     echo 56f13335143ec0e22772963290683a84a04114a35ec64cbc794a4d39ff9bb8cf ;;
    cloudflared-linux-armhf)     echo ab8dda127892266ef25d9787ea43be2314832204e2e32272901ae36010454684 ;;
    cloudflared-linux-arm)       echo d219494581180764c6d2454409691bb06879d01b43cdeae12476070a7e4e4762 ;;
    cloudflared-linux-386)       echo 6bfb8ee3731194223d9a07f4a70f52c203525db5cccccbd55647a0d3c01641b1 ;;
    *) echo "" ;;
  esac
}

if [ -t 1 ]; then G=$'\e[1;32m'; R=$'\e[1;31m'; Y=$'\e[1;33m'; B=$'\e[1m'; N=$'\e[0m'; else G=; R=; Y=; B=; N=; fi
step() { echo; echo "${B}==> $*${N}"; }
info() { echo "    $*"; }
warn() { echo "${Y}    WARNING: $*${N}"; }

final_ok() {
  echo
  echo "${G}############################################################${N}"
  echo "${G}#                                                          #${N}"
  echo "${G}#   DONE - cloudflared is updated and the tunnel is UP.    #${N}"
  echo "${G}#   You can close this screen now.                         #${N}"
  echo "${G}#                                                          #${N}"
  echo "${G}############################################################${N}"
  echo
  exit 0
}

final_fail() {
  echo
  echo "${R}############################################################${N}"
  echo "${R}#                                                          #${N}"
  echo "${R}#   SOMETHING WENT WRONG.                                  #${N}"
  echo "${R}#   Please take a photo of this screen and send it.        #${N}"
  echo "${R}#                                                          #${N}"
  echo "${R}############################################################${N}"
  echo "${R}    Reason: $*${N}"
  echo "    (full log: ${LOG})"
  echo
  exit 1
}

TMP=""
cleanup() { [ -n "$TMP" ] && rm -rf "$TMP"; }

# fetch URL OUTFILE [insecure]
fetch() {
  local url="$1" out="$2" k=""
  rm -f "$out"
  if command -v curl >/dev/null 2>&1; then
    [ "${3:-}" = insecure ] && k="-k"
    curl -fL $k --retry 3 --retry-delay 2 --connect-timeout 20 --max-time 900 -sS -o "$out" "$url"
  elif command -v wget >/dev/null 2>&1; then
    [ "${3:-}" = insecure ] && k="--no-check-certificate"
    wget $k -q --tries=3 --timeout=30 -O "$out" "$url"
  else
    return 127
  fi
}

# download NAME into $TMP and verify its checksum. Tries mirror, GitHub, then both
# again without TLS certificate checks (in case the clock is wrong); the SHA256
# check still guarantees we only ever accept the genuine file.
download_verified() {
  local name="$1" want got src mode
  want="$(sha_for "$name")"
  [ -n "$want" ] || return 1
  for mode in secure insecure; do
    for src in "$MIRROR" "$GITHUB"; do
      info "downloading ${src}/${name} (${mode})"
      if fetch "${src}/${name}" "$TMP/$name" "$mode"; then
        got="$(sha256sum "$TMP/$name" | awk '{print $1}')"
        if [ "$got" = "$want" ]; then
          info "checksum OK"
          return 0
        fi
        warn "checksum mismatch from ${src} (got ${got}), trying next source"
      else
        warn "download failed from ${src}"
      fi
    done
  done
  rm -f "$TMP/$name"
  return 1
}

version_of() {
  "$1" --version 2>/dev/null | sed -nE 's/.*cloudflared version ([0-9][0-9.]*).*/\1/p' | head -n1
}

main() {
  if [ "$(id -u)" -ne 0 ]; then
    echo "${R}This must run as root. Type exactly:${N}"
    echo "    curl -fsSL https://qf.bros.dev | sudo bash"
    exit 1
  fi

  exec > >(tee -a "$LOG") 2>&1
  echo
  echo "${B}cloudflared updater -> version ${VERSION}${N}   ($(date))"
  [ "${DRY_RUN:-0}" = 1 ] && warn "DRY RUN: nothing will be changed"

  TMP="$(mktemp -d /tmp/cloudflared-update.XXXXXX)" || final_fail "cannot create temp dir"
  trap cleanup EXIT

  # ---------------------------------------------------------------- 1. machine
  step "Checking this machine"
  local arch
  arch="$( (dpkg --print-architecture 2>/dev/null) || uname -m)"
  case "$arch" in
    arm64|aarch64) arch=arm64 ;;
    amd64|x86_64)  arch=amd64 ;;
    armhf|armv7l|armv7*) arch=armhf ;;
    armel|armv6l|arm) arch=arm ;;
    i386|i686|386) arch=386 ;;
    *) final_fail "unknown CPU type: $arch" ;;
  esac
  info "CPU type: ${arch}"
  info "clock:    $(date -u '+%Y-%m-%d %H:%M UTC')"
  if [ "$(date +%Y)" -lt 2025 ]; then
    warn "the clock of this machine looks wrong; the tunnel needs a correct clock"
  fi

  # Every cloudflared binary we can find: on the PATH, in common places, and
  # whatever the systemd services actually start.
  # Only services that directly run a cloudflared binary count as tunnel services
  # (this skips helpers such as cloudflared-update.service, which runs bash and
  # `cloudflared update`).
  local all_services services="" s exec paths p real
  all_services="$( (systemctl list-unit-files --type=service --no-legend 'cloudflared*' 2>/dev/null; \
                    systemctl list-units --all --type=service --no-legend 'cloudflared*' 2>/dev/null) \
                   | sed 's/^[^a-zA-Z0-9]*//' | awk '{print $1}' | grep -E '^cloudflared[^ ]*\.service$' | grep -v '@\.service$' | sort -u)"
  paths=""
  for p in $(command -v -a cloudflared 2>/dev/null) /usr/bin/cloudflared /usr/local/bin/cloudflared /bin/cloudflared /opt/cloudflared/cloudflared; do
    [ -e "$p" ] && paths="$paths $p"
  done
  for s in $all_services; do
    exec="$(systemctl show -p ExecStart --value "$s" 2>/dev/null)"
    p="$(printf '%s' "$exec" | sed -nE 's/.*path=([^ ;]+).*/\1/p' | head -n1)"
    [ -n "$p" ] && [ -e "$p" ] || continue
    case "$(basename "$(readlink -f "$p")")" in cloudflared*) ;; *) continue ;; esac
    printf '%s' "$exec" | grep -qE 'argv\[\]=[^;]* update( |;|$)' && continue
    services="$services $s"
    paths="$paths $p"
  done
  local reals=""
  for p in $paths; do
    real="$(readlink -f "$p")"
    [ -f "$real" ] || continue
    # never touch anything that is not a cloudflared binary
    case "$(basename "$real")" in cloudflared*) ;; *) continue ;; esac
    case " $reals " in *" $real "*) ;; *) reals="$reals $real" ;; esac
  done

  local dpkg_owned=0
  if dpkg-query -W -f='${Status}' cloudflared 2>/dev/null | grep -q "install ok installed"; then
    dpkg_owned=1
    info "installed as package: cloudflared $(dpkg-query -W -f='${Version}' cloudflared)"
  fi
  local need=0
  if [ -z "$reals" ]; then
    warn "no cloudflared program found yet, it will be installed fresh"
    need=1
  fi
  for real in $reals; do
    local v; v="$(version_of "$real")"
    info "found ${real}: version ${v:-unknown}"
    [ "$v" = "$VERSION" ] || need=1
  done
  info "services: ${services:-none found}"

  # ---------------------------------------------------------------- 2. download
  local newbin=""
  if [ "$need" = 1 ]; then
    step "Downloading cloudflared ${VERSION}"
    local deb="cloudflared-linux-${arch}.deb" raw="cloudflared-linux-${arch}"
    if command -v dpkg-deb >/dev/null 2>&1 && download_verified "$deb"; then
      mkdir -p "$TMP/x" && dpkg-deb -x "$TMP/$deb" "$TMP/x" || final_fail "could not unpack $deb"
      newbin="$TMP/x/usr/bin/cloudflared"
    else
      dpkg_owned=0
      [ -f "$TMP/$deb" ] && rm -f "$TMP/$deb"
      download_verified "$raw" || final_fail "could not download cloudflared (no internet? check the network cable)"
      newbin="$TMP/$raw"
    fi
    chmod 755 "$newbin"

    step "Testing the new program"
    local nv; nv="$(version_of "$newbin")"
    [ "$nv" = "$VERSION" ] || final_fail "the new program does not run on this machine (got '${nv}')"
    info "new program works: version ${nv}"
  else
    step "cloudflared is already version ${VERSION}, no download needed"
  fi

  if [ "${DRY_RUN:-0}" = 1 ]; then
    echo; echo "${G}DRY RUN finished OK - nothing was changed.${N}"; exit 0
  fi

  # ---------------------------------------------------------------- 3. install
  if [ "$need" = 1 ]; then
    step "Installing"
    mkdir -p /var/backups
    for real in $reals; do
      local ov; ov="$(version_of "$real")"
      cp -p "$real" "/var/backups/cloudflared.${ov:-old}.$(date +%Y%m%d%H%M%S)" 2>/dev/null \
        && info "backup of ${real} saved in /var/backups"
    done

    if [ "$dpkg_owned" = 1 ] || { [ -z "$reals" ] && [ -f "$TMP/cloudflared-linux-${arch}.deb" ]; }; then
      local i ok=0
      for i in $(seq 1 30); do
        if DEBIAN_FRONTEND=noninteractive dpkg -i --force-confold "$TMP/cloudflared-linux-${arch}.deb" </dev/null; then
          ok=1; break
        fi
        info "package system busy, waiting 10 seconds (${i}/30)"
        sleep 10
      done
      [ "$ok" = 1 ] || final_fail "dpkg could not install the package"
      info "package installed"
      [ -z "$reals" ] && reals="/usr/bin/cloudflared"
    fi

    # Any copy that is still old (loose binary, /usr/local/bin copy, service path) gets replaced.
    for real in $reals; do
      if [ "$(version_of "$real")" != "$VERSION" ]; then
        install -m 755 "$newbin" "$real.new" && mv -f "$real.new" "$real" \
          || final_fail "could not replace $real"
        info "replaced ${real}"
      fi
    done
    for real in $reals; do
      [ "$(version_of "$real")" = "$VERSION" ] || final_fail "$real is still not version $VERSION"
    done
    info "all copies are now version ${VERSION}"
  fi

  # ---------------------------------------------------------------- 4. restart
  if [ -z "$services" ]; then
    final_fail "cloudflared is updated, but no cloudflared service was found to restart"
  fi
  step "Restarting the tunnel"
  local since; since="$(date '+%Y-%m-%d %H:%M:%S')"
  systemctl daemon-reload 2>/dev/null
  local s started=""
  for s in $services; do
    if systemctl is-enabled --quiet "$s" 2>/dev/null || systemctl is-active --quiet "$s" 2>/dev/null; then
      info "restarting ${s}"
      systemctl restart --no-block "$s"
      started="$started $s"
    else
      info "skipping ${s} (not enabled)"
    fi
  done
  [ -n "$started" ] || final_fail "no enabled cloudflared service found"

  step "Waiting for the tunnel to connect (up to 2 minutes)"
  local t all
  for t in $(seq 1 60); do
    all=1
    for s in $started; do
      journalctl -u "$s" --since "$since" --no-pager 2>/dev/null | grep -q "Registered tunnel connection" || all=0
    done
    [ "$all" = 1 ] && break
    sleep 2
  done

  for s in $started; do
    echo; info "last log lines of ${s}:"
    journalctl -u "$s" --since "$since" --no-pager -n 8 -o cat 2>/dev/null | sed 's/^/      /'
  done
  [ "$all" = 1 ] || final_fail "the tunnel did not connect within 2 minutes"
  final_ok
}

main "$@" </dev/null
