#!/bin/bash

# https://www.baeldung.com/ops/docker-container-auto-update-newest-base-images
# https://containrrr.dev/watchtower/notifications/

source /opt/scripts_remote/shared_functions.sh

set -euo pipefail

type -p docker >/dev/null || {
  echo "Docker not installed. Exiting."
  exit 0
}

# `docker ps -q` prints the IDs of running containers, one per line.
if docker ps -q | grep -q .; then
  echo "At least one container is running. Checking for updates."
  HC_ID=28548ef7-451e-4640-bda2-834ce7031be1
  TGRAM_PARAM=telegram://6509310953:AAGPUjeRpTyuQZ9rnU62XbMsDQ06sWUYW4M@telegram/?chats=-1001730456573

  # -- notifications hostname
  SERVER_NAME="$(hostname)"

  
  MY_NOTIF_TEMPLATE='{{- if .Report -}}
  {{- $u := .Report.Updated -}}
  {{- $f := .Report.Failed  -}}
  {{- if or (gt (len $u) 0) (gt (len $f) 0) -}}
  {{ .Host }}:{{- if gt (len $u) 0 }} {{- range $i, $c := $u}}{{if $i}}, {{end}}{{ $c.Name }}{{end}}{{- end -}}{{- if gt (len $f) 0 }}; FAILED: {{- range $i, $c := $f}}{{if $i}}, {{end}}{{ $c.Name }}{{end}}{{- end }}
  {{- end -}}{{- end -}}'
  
  # -- template
  # MY_NOTIF_TEMPLATE='{{- if .Report -}}{{- if gt (len .Report.Updated) 0 -}}
  # {{ .Host }}:{{- range $i, $c := .Report.Updated }}{{ if $i }}, {{ end }}{{ $c.Name }}{{- end }}
  # {{- end -}}{{- end -}}'


  # MY_NOTIF_TEMPLATE="{{- if .Report -}}{{- with .Report -}}{{- if ( or .Updated .Failed ) -}} 
  # {{len .Scanned}} Scanned, {{len .Updated}} Updated, {{len .Failed}} Failed{{- range .Updated}}
  # - {{.Name}} ({{.ImageName}}): {{.CurrentImageID.ShortID}} updated to {{.LatestImageID.ShortID}}
  # {{- end -}}{{- range .Fresh}}- {{.Name}} ({{.ImageName}}): {{.State}}{{- end -}}{{- range .Skipped}}
  # - {{.Name}} ({{.ImageName}}): {{.State}}: {{.Error}}{{- end -}}{{- range .Failed}}- {{.Name}} 
  # ({{.ImageName}}): {{.State}}: {{.Error}}{{- end -}}{{- end -}}{{- end -}}
  # {{- else -}}{{range .Entries -}}{{.Message}}{{'\n'}}{{- end -}}{{- end -}}"

  echo "Starting checking and updating containers."

  docker run --rm  \
    -v /var/run/docker.sock:/var/run/docker.sock  \
    -v /etc/localtime:/etc/localtime:ro \
    containrrr/watchtower \
    --run-once \
    --cleanup \
    --include-restarting \
    --no-startup-message \
    --monitor-only=false \
    --log-level=warn \
    --remove-volumes \
    --notifications-hostname="$SERVER_NAME" \
    --notification-url="$TGRAM_PARAM" \
    --notification-report=true \
    --notification-template="$MY_NOTIF_TEMPLATE"
else
  echo "No containers are running. No update required."
  exit 0
fi