{{- if and (ne .user.CLOUDFLARE_ACCESS_KEY_ID "") (ne .user.CLOUDFLARE_SECRET_ACCESS_KEY "") (ne .user.CLOUDFLARE_R2_ACCOUNT_ID "") }}
#!/usr/bin/env bash

# Consider https://github.com/dustinsand/blockinfile
CONFIG_FILE="$HOME/.config/rclone/rclone.conf"
if cat "$CONFIG_FILE" | grep '# MEGABYTE LABS MANAGED r2-user'; then
  # TODO: Remove old block
  START_LINE="$(echo `grep -n -m 1 "# MEGABYTE LABS MANAGED r2-user" .zshrc | cut -f1 -d ":"`)"
  END_LINE="$(echo `grep -n -m 1 "# MEGABYTE LABS MANAGED r2-user" .zshrc | cut -f1 -d ":"`)"
  if command -v gsed > /dev/null; then
    gsed -i "$START_LINE,$END_LINEd" "$CONFIG_FILE"
  else
    sed -i "$START_LINE,$END_LINEd" "$CONFIG_FILE"
  fi
fi

tee -a "$CONFIG_FILE" > /dev/null <<EOT
# MEGABYTE LABS MANAGED r2-user
[r2-user]
type = s3
provider = Cloudflare
access_key_id = {{ .user.CLOUDFLARE_ACCESS_KEY_ID }}
secret_access_key = {{ .user.CLOUDFLARE_SECRET_ACCESS_KEY }}
region = auto
endpoint = https://{{ .user.CLOUDFLARE_R2_ACCOUNT_ID }}.r2.cloudflarestorage.com
acl = private
# MEGABYTE LABS MANAGED r2-user
EOT
{{- end }}
