#!/bin/bash
#
# shellcheck disable=SC1091,SC2086,SC2181,SC2207
#
# Copyright (c) 2023-2024 OpenMediaVault Plugin Developers
#
# This file is licensed under the terms of the GNU General Public
# License version 2. This program is licensed "as is" without any
# warranty of any kind, whether express or implied.
#
# version: 1.0.4

export LANG=C.UTF-8

. /usr/share/openmediavault/scripts/helper-functions

declare -i force=0
declare -i i=0
declare -i j=0

# logging location
logDir="/var/log/"
logFile="${logDir}/omv-compose-backup.log"

_log()
{
  msg=${1}
  echo "[$(date +'%Y-%m-%d %H:%M:%S%z')] [composebackup] ${msg}" | tee -a ${logFile} >&2
}

extractContPath() {
  local val="$1"
  # Remove everything before the first colon
  val="${val#*:}"
  # Remove anything after a '#' (comment)
  val="${val%%#*}"
  # Remove everything after the next colon
  val="${val%%:*}"
  # Trim trailing whitespace
  val="${val%"${val##*[![:space:]]}"}"
  echo "${val}"
}

compose="${1}"
if [ -z "${compose}" ]; then
  _log "No compose name set.  Exiting..."
  exit 10
fi
_log "compose :: ${compose}"

# Get docker storage path
dockerStorage=$(omv_config_get "/config/services/compose/dockerStorage")
_log "Docker storage :: ${dockerStorage}"

# Get the shared folder reference and path
sfref=$(omv_config_get "/config/services/compose/sharedfolderref")
if ! omv_isuuid "${sfref}"; then
  _log "No compose sharedfolder set."
  exit 11
fi
sfpath="$(omv_get_sharedfolder_path "${sfref}")"
if [ ! -d "${sfpath}" ]; then
  _log "Shared folder directory does not exist.  Exiting..."
  exit 12
fi
sfpath="${sfpath/%\/}"
sfpath="${sfpath//\/\//\/}"
_log "Compose file path :: ${sfpath}"

# Get the backup shared folder reference and path
sfref=$(omv_config_get "/config/services/compose/backupsharedfolderref")
if ! omv_isuuid "${sfref}"; then
  _log "No backup sharedfolder set."
  exit 13
fi
backuppath="$(omv_get_sharedfolder_path "${sfref}")"
if [ ! -d "${backuppath}" ]; then
  _log "Backup shared folder directory does not exist.  Exiting..."
  exit 14
fi
backuppath="${backuppath/%\/}"
backuppath="${backuppath//\/\//\/}"
_log "Backup path :: ${backuppath}"

# set path for yml and env files
composepath="${sfpath}/${compose}"
env="${composepath}/${compose}.env"
globalenv="${sfpath}/global.env"
yml="${composepath}/${compose}.yml"
ovr="${composepath}/compose.override.yml"
if [ ! -f "${yml}" ]; then
  _log "Compose file '${yml}' does not exist.  Exiting..."
  exit 15
fi
_log "Compose file :: ${yml}"

yq="/usr/local/bin/yq"
if [ ! -f "${yq}" ]; then
  _log "'${yq}' does not exist.  Exiting..."
  exit 16
fi

# Get the backup max size
backupmaxsize=$(omv_config_get "/config/services/compose/backupmaxsize")
if [ ${backupmaxsize} -lt 1 ]; then
  _log "Backup max size is set to unlimited."
  backupmaxsize=0
fi
_log "Backup max size :: ${backupmaxsize} GB"
backupmax=$((backupmaxsize * 1024 * 1024 * 1024))

OFS=$IFS
IFS=$'\n'

# build compose arguments
dockerComposeArgs=("--file" "${yml}")
if [ -f "${ovr}" ]; then
  dockerComposeArgs+=("--file" "${ovr}")
fi
if [ -f "${globalenv}" ]; then
  dockerComposeArgs+=("--env-file" "${globalenv}")
fi
dockerComposeArgs+=("--env-file" "${env}")

# run docker compose config
confout="$(mktemp)"
docker compose "${dockerComposeArgs[@]}" config --output "${confout}"
if [ $? -gt 0 ] || [ -z "${confout}" ]; then
  _log "Failed to run docker compose config.  Exiting..."
  exit 17
fi

# get volumes
ymlVols=($(${yq} '.services[] | .volumes' "${yml}" | grep '^- ' | sed 's/^- //' | sed 's/"//g'))
confVols=($(${yq} eval '.services[].volumes[]? | .source + ":" + .target' "${confout}"))

IFS=$OFS

# create backup subdirectory
backupdir="${backuppath}/${compose}"
mkdir -pv "${backupdir}"

# update volume list
vollist="${backupdir}/vol.list"
echo "${i},${composepath}" > "${vollist}"

# save status
status="$(mktemp)"
docker compose ls --all --format json | jq -r ".[] | select(.ConfigFiles | contains(\"${yml}\")) | .Status" > "${status}"
_log "status :: $(cat "${status}")"

# stop compose if running
if grep -q "running" "${status}"; then
  docker compose "${dockerComposeArgs[@]}" stop
else
  _log "${compose} is not running"
fi

# copy yml and env files and other files that use a relative path
voldir="${backupdir}/${i}"
mkdir -pv "${voldir}"
cp -v "${yml}" "${ovr}" "${env}" "${voldir}/"

# loop through volumes
for vol in "${confVols[@]}"; do
  # container path
  contpath="${vol#*:}"
  cmt=""
  for item in "${ymlVols[@]}"; do
    contitem=$(extractContPath "${item}")
    if [[ "${contpath%/}" == "${contitem%/}" ]]; then
      cmt="${item}"
      break
    fi
  done
  if [ -z "${cmt}" ]; then
    _log "no docker compose config match found for ${vol}"
    continue
  fi
  # host path
  hostpath="${vol%%:*}"
  hostpath="${hostpath//\'/}"
  _log "Volume :: ${vol}"
  # check for paths to skip or force
  if [[ "${cmt}" == *"SKIP_BACKUP"* ]]; then
    _log "Skipping for SKIP_BACKUP comment :: ${vol}"
    echo
    continue
  elif [[ "${hostpath}" == @(/dev|/dev/*|/lib|/lib/*|/sys|/sys/*|./*|../*|/) ]]; then
    _log "Skipping :: ${hostpath}"
    echo
    continue
  elif [[ "${cmt}" == *":ro"* ]]; then
    _log "Read only volume. Skipping :: ${hostpath}"
    echo
    continue
  elif [[ "${hostpath}" != *"/"* ]]; then
    _log "Named volume. Skipping :: ${hostpath}"
    echo
    continue
  elif [[ "${cmt}" == *"BACKUP"* ]]; then
    _log "Forcing for BACKUP comment :: ${vol}"
    force=1
  else
    _log "Backup host path :: ${hostpath}"
    force=0
  fi
  if [ ! -f "${hostpath}" ] && [ ! -d "${hostpath}" ]; then
    if [ -e "${hostpath}" ]; then
      _log "Special file. Skipping..."
      echo
    else
      _log "Path does not exist. Skipping..."
      echo
    fi
    continue
  fi
  if [ ${backupmaxsize} -gt 0 ]; then
    foldersize=$(du --summarize --bytes "${hostpath}" | awk '{ print $1 }')
    _log "Folder size :: ${foldersize} bytes"
    if [ ${foldersize} -gt ${backupmax} ] && [ ${force} -eq 0 ]; then
      _log "Folder size greater than max backup size.  Skipping..."
      continue;
    fi
  fi
  if cut -d"," -f2 "${vollist}" | sed 's#/$##' | grep -Fqx "${hostpath%/}"; then
    _log "Duplicate volume path '${hostpath}' - skipping..."
  else
    ((i++))
    # rsync to numbered subdirectory
    voldir="${backupdir}/${i}"
    mkdir -pv "${voldir}"
    _log "Backup to :: ${voldir}"
    exclude=""
    if [ -d "${hostpath}" ]; then
      hostpath="${hostpath}/"
      if [ "${force}" -ne 1 ]; then
        exclude="--exclude *.qcow2"
      fi
    fi
    # add volume list entry
    echo "${i},${hostpath}" >> "${vollist}"
    # rsync
    rsync -avr --delete ${exclude} "${hostpath}" "${voldir}"
  fi
  echo
done

# remove extra directories from a previous backup
# if a volume(s) were removed from the compose file.
while [ ${i} -le 100 ] && [ ${j} -le 3 ]; do
  ((i++))
  voldir="${backupdir}/${i}"
  if [ -d "${voldir}" ]; then
    _log "Removing '${voldir}' directory from previous backup that is no longer in compose file."
    rm -rf "${voldir}"
  else
    ((j++))
  fi
done

# start compose if running before backup
if grep -q "running" "${status}"; then
  docker compose "${dockerComposeArgs[@]}" start
fi

# store size of backup
spaceused="${backupdir}/space.used"
backupsize=$(du --summarize --bytes "${backupdir}" | awk '{ print $1 }')
_log "Backup size :: ${backupsize} bytes"
echo ${backupsize} > "${spaceused}"

# remove temp files
rm -f "${confout}" "${status}"

_log "Done."

exit 0
