penguin/utils

my env utils

bash/core/50_upgrade.bash

raw ยท 1935 bytes

rbash-upgrade() {
  local target url tmp rendered backup
  local host domain color content

  target="$__RBASH_SCRIPT"
  url="$(rbash_url "rbashrc")"

  host="${1:-$RHOSTNAME}"
  domain="${2:-$RDOMAIN}"
  color="${3:-$RCOLOR}"

  echo "Updating $target"

  tmp="$(mktemp "${TMPDIR:-/tmp}/rbashrc.download.XXXXXX")" || return 1
  rendered="$(mktemp "${TMPDIR:-/tmp}/rbashrc.rendered.XXXXXX")" || {
    rm -f "$tmp"
    return 1
  }

  if ! rbash_download "$url" > "$tmp"; then
    echo "rbash: upgrade download failed: $url" >&2
    rm -f "$tmp" "$rendered"
    return 1
  fi

  if [ ! -s "$tmp" ]; then
    echo "rbash: downloaded rbashrc is empty; refusing to install" >&2
    rm -f "$tmp" "$rendered"
    return 1
  fi

  content="$(cat "$tmp")"

  content="${content//<HOSTNAME>/$host}"
  content="${content//<DOMAIN>/$domain}"
  content="${content//<RCOLOR>/$color}"

  printf '%s\n' "$content" > "$rendered" || {
    echo "rbash: failed to render new rbashrc" >&2
    rm -f "$tmp" "$rendered"
    return 1
  }

  if ! grep -q 'RBASH_HOME' "$rendered"; then
    echo "rbash: rendered file does not look like rbashrc; refusing to install" >&2
    rm -f "$tmp" "$rendered"
    return 1
  fi

  if ! bash -n "$rendered"; then
    echo "rbash: rendered rbashrc has syntax errors; refusing to install" >&2
    rm -f "$tmp" "$rendered"
    return 1
  fi

  backup="$target.bak.$(date +%Y%m%d%H%M%S)"

  if [ -f "$target" ]; then
    cp "$target" "$backup" || {
      echo "rbash: failed to create backup: $backup" >&2
      rm -f "$tmp" "$rendered"
      return 1
    }
    echo "Backup: $backup"
  fi

  chmod 700 "$rendered"

  if ! mv "$rendered" "$target"; then
    echo "rbash: failed to replace $target" >&2
    echo "rbash: backup remains at $backup" >&2
    rm -f "$tmp" "$rendered"
    return 1
  fi

  rm -f "$tmp"

  rm -rf "$RBASH_CACHE_DIR"
  mkdir -p "$RBASH_CACHE_DIR"

  # shellcheck source=/dev/null
  source "$target"
}