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

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

declare -i esp=0
declare -i threads=1

arch=$(uname --machine)
threads=$(nproc --all | awk '{print ($1 > 32) ? 32 : $1}')

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

# Shim to write messages to stdout and to the logfile.
_log_export()
{
  echo "[$(date +'%Y-%m-%d %H:%M:%S%z')] [backup] ${msg}" | tee -a ${logFile} >&2
}

_log()
{
  msg=${1}
  _log_export "$(omv_log "${msg}")"
}

# Level for recoverable errors.
_log_warning()
{
  msg=${1}
  _log_export "$(omv_warning "${msg}")"
}

# Level for unrecoverable errors that would be write to stderr an to the logfile.
_log_error()
{
  msg=${1}
  echo "[$(date +'%Y-%m-%d %H:%M:%S%z')] [backup] $(omv_error "${msg}" 2>&1)" > >(tee -a ${logFile} >&2)
}

purgeOld()
{
  # get number of days to keep
  keep=$(omv_config_get "/config/system/backup/keep")
  _log "keep days :: ${keep}"
  if [[ ${keep} -gt 0 ]]; then
    _log "Purging old files ..."
    find "${backupDir}" -maxdepth ${OMV_BACKUP_MAX_DEPTH} -type f -mtime +${keep} -name "${OMV_BACKUP_FILE_PREFIX}*" -delete
    if [ $? -eq 0 ]; then
      _log "Purging done."
    else
      _log_warning "Purge failed!"
    fi
  else
    _log "Purging disabled."
  fi
}

_log "Starting backup ..."
_log "threads :: ${threads}"
_log "arch :: ${arch}"

# date
date=$(date +"%Y-%m-%d_%H-%M-%S")

# clean apt-get cache to save space
apt-get clean

# clean openmediavault upload cache and recreate Packages file
rm -f /var/cache/openmediavault/archives/*
touch /var/cache/openmediavault/archives/Packages

# Get the shared folder reference and path
sfref=$(omv_config_get "/config/system/backup/sharedfolderref")
if ! omv_isuuid "${sfref}"; then
  _log_error "No backup volume set.  Please choose a backup volume."
  exit 10
fi
sfpath="$(omv_get_sharedfolder_path "${sfref}")"
if [ ! -d "${sfpath}" ]; then
  _log_error "Shared folder directory does not exist.  Exiting."
  exit 11
fi

# get verbose setting
verbose=$(omv_config_get "/config/system/backup/verbose")

# set backup directory and create it if it doesn't exist
backupDir="${sfpath}/${OMV_BACKUP_DIR_NAME}"
_log "Create ${backupDir}"
mkdir -p "${backupDir}"

# Get the method of backup
method=$(omv_config_get "/config/system/backup/method")
_log "Method: ${method}"

# get device file for /
devicefile=$(awk '$5 == "/" { print $10 }' /proc/self/mountinfo)
_log "Device file:  ${devicefile}"

# try alternate method to get root device if /dev/root is returned
if [ "${devicefile}" = "/dev/root" ]; then
  devicefile=$(findmnt -n / | awk '{ print $2 }')
fi

if [ "${devicefile}" = "/dev/root" ] || [ -z "${devicefile}" ]; then
  _log_error "Could not determine root device file. Please specify in the root device textbox. Exiting."
  exit 12
fi

# get root device
root=$(omv_config_get "/config/system/backup/root")

# if root is empty, try to determine root device
if [ -z "${root}" ]; then
  root="/dev/$(lsblk -no pkname ${devicefile})"
else
  _log "Using actual device for ${root}"
  root="$(readlink -f "${root}")"
fi
_log "Root drive: ${root}"

if [ -z "${root}" ]; then
  _log_error "Could not determine root device.  Exiting."
  exit 13
fi

# save helpful information
_log "Save fdisk output for ${root}"
fdisk --list ${root} > "${backupDir}/${OMV_BACKUP_FILE_PREFIX}-${date}.fdisk"
if [ $? -eq 0 ]; then
  _log "Successfully saved fdisk output for ${root}"
else
  _log_warning "Save of fdisk output for ${root} failed!"
fi
_log "Save blkid output"
blkid > "${backupDir}/${OMV_BACKUP_FILE_PREFIX}-${date}.blkid"
if [ $? -eq 0 ]; then
  _log "Successfully saved blkid output"
else
  _log_warning "Save of blkid output failed!"
fi
_log "Save package list"
dpkg --list | grep openmediavault > "${backupDir}/${OMV_BACKUP_FILE_PREFIX}-${date}.packages"
if [ $? -eq 0 ]; then
  _log "Successfully saved package list"
else
  _log_warning "Save of package list failed!"
fi

# zstd profile selector
if [ -z "${OMV_BACKUP_ZSTD_OPTIONS}" ]; then
  if [ "${threads}" -eq 1 ] && [[ "${arch}" = "armv"* ]]; then
    OMV_BACKUP_ZSTD_OPTIONS="--fast=5"
  elif [[ "${arch}" = "armv"* ]]; then
    OMV_BACKUP_ZSTD_OPTIONS="-T0 --fast"
  elif [ ${OMV_BACKUP_ZSTD_ADAPT} -eq 1 ]; then
    OMV_BACKUP_ZSTD_OPTIONS="-T0 --adapt --long"
  else
    OMV_BACKUP_ZSTD_OPTIONS="-T0 --long"
  fi
fi

# calculate partition table size to accommodate GPT and MBR.
part_type=$(blkid --probe ${root} | cut -d \" -f4)
_log "Partition type :: ${part_type}"
if [ "${part_type}" = "gpt" ]; then
  num_parts=$(parted -m ${root} print | tail -n1 | cut -b1)
  grubparts_bs_calc=$(((128 * num_parts) + 1024))
  esp=$(parted -m ${root} print | awk -F ":" '$7 ~ /esp/ { print $1 }')
  if [ ${esp} -lt 1 ]; then
    _log "ESP partition not found."
  else
    partletter=""
    if [[ ${root} =~ nvme ]]; then
      partletter="p"
    fi
    esppart="${root}${partletter}${esp}"
    _log "ESP partition :: ${esppart}"
    if [ -e "${esppart}" ]; then
      # add verbose flag if verbose is enabled
      vb=""
      if [ ${verbose} -eq 1 ]; then
        vb=" --verbose"
      fi
      fstrim /boot/efi
      _log "Backup ESP partition"
      zstd ${OMV_BACKUP_ZSTD_OPTIONS}${vb} -o "${backupDir}/${OMV_BACKUP_FILE_PREFIX}-${date}.espdd.zst" < "${esppart}"
      if [ $? -eq 0 ]; then
        _log "Successfully backuped ESP partition"
      else
        _log_warning "Backup of ESP partition failed!"
      fi
    else
      _log "ESP partition '${esppart}' not found."
    fi
  fi
else
  grubparts_bs_calc=512
fi


# save partition table and mbr
_log "Save mbr"
dd if=${root} of="${backupDir}/${OMV_BACKUP_FILE_PREFIX}-${date}.grub" bs=446 count=1
if [ $? -eq 0 ]; then
  _log "Successfully saved MBR"
else
  _log_warning "Save of MBR failed!"
fi
_log "Save mbr and partition table"
dd if=${root} of="${backupDir}/${OMV_BACKUP_FILE_PREFIX}-${date}.grubparts" bs=${grubparts_bs_calc} count=1
if [ $? -eq 0 ]; then
  _log "Successfully saved MBR and partition table"
else
  _log_warning "Save of MBR and partition table failed!"
fi

# Save partition table using sfdisk
_log "Save partitions using sfdisk"
sfdisk --dump ${root} > "${backupDir}/${OMV_BACKUP_FILE_PREFIX}-${date}.sfdisk"
if [ $? -eq 0 ]; then
  _log "Successfully saved partition table using sfdisk"
else
  _log_warning "Save of sfdisk partition table failed"
fi

# check for /boot partition
bootpart=$(awk '$2 == "/boot" { print $1 }' /proc/mounts)
if [ ! -b "${bootpart}" ]; then
  bootpart=""
else
  _log "Boot drive: ${bootpart}"
fi

# backup u-boot if platform_install.sh exists
if [ -f "/usr/lib/u-boot/platform_install.sh" ]; then
  . /usr/lib/u-boot/platform_install.sh
  if [ -d "${DIR}" ]; then
    _log "Backup u-boot"
    tar --create --zstd --file "${backupDir}/${OMV_BACKUP_FILE_PREFIX}-${date}_u-boot.tar.zst" ${DIR}/*
    if [ $? -eq 0 ]; then
      _log "Successfully backuped u-boot"
    else
      _log_warning "Backup of u-boot failed!"
    fi
  fi
fi

# perform backup based on method selected
case ${method} in
  dd)
    vb=""
    if [ ${verbose} -eq 1 ]; then
      vb=" --verbose"
    else
      vb=" --quiet"
    fi
    _log "Running fstrim on / ..."
    fstrim /
    _log "Starting dd backup ..."
    zstd ${OMV_BACKUP_ZSTD_OPTIONS}${vb} -v -o "${backupDir}/${OMV_BACKUP_FILE_PREFIX}-${date}.dd.zst" <"${devicefile}"
    if [[ $? -gt 0 ]]; then
      _log_error "zstd exit code = $?"
      _log_error "dd backup failed!"
      exit 14
    else
      _log "dd backup complete."
    fi
    sync
    if [ -n "${bootpart}" ]; then
      _log "Running fstrim on /boot ..."
      fstrim /boot/
      _log "Starting dd backup of boot partition ..."
      zstd ${OMV_BACKUP_ZSTD_OPTIONS}${vb} -o "${backupDir}/${OMV_BACKUP_FILE_PREFIX}-${date}_boot.dd.zst" <"${bootpart}"
      if [ $? -eq 0 ]; then
        _log "dd backup of boot partition complete."
      else
        _log_error "zstd exit code = $?"
        _log_error "dd backup of boot partition failed!"
        exit 15
      fi
    fi
    sync
    touch "${backupDir}/${OMV_BACKUP_FILE_PREFIX}"-${date}*.dd.zst
    purgeOld
    ;;

  ddfull)
    vb=""
    if [ ${verbose} -eq 1 ]; then
      vb=" --verbose"
    else
      vb=" --quiet"
    fi
    for mp in $(lsblk --noheadings --output MOUNTPOINT ${root}); do
      _log "Running fstrim on ${mp} ..."
      fstrim "${mp}"
    done
    _log "Starting dd full disk ..."
    zstd ${OMV_BACKUP_ZSTD_OPTIONS}${vb} -o "${backupDir}/${OMV_BACKUP_FILE_PREFIX}-${date}.ddfull.zst" < "${root}"
    if [[ $? -gt 0 ]]; then
      _log_error "zstd exit code = $?"
      _log_error "dd full disk backup failed!"
      exit 16
    else
      _log "dd full disk backup complete."
    fi
    sync
    sync
    touch "${backupDir}/${OMV_BACKUP_FILE_PREFIX}"*-${date}.ddfull.zst
    purgeOld
    ;;

  fsarchiver)
    # add progress flag if verbose is enabled
    vb=""
    if [ ${verbose} -eq 1 ]; then
      vb=" -v"
    fi
    _log "Starting FSArchiver backup ..."
    extra=$(omv_config_get "/config/system/backup/extraoptions")
    passwd="$(omv_config_get "/config/system/backup/passwd")"
    password=""
    if [ -n "${passwd}" ]; then
      _log "Encrypting archive ..."
      password="--cryptpass=${passwd} "
    fi
    fsarchiver savefs ${password}-o "${backupDir}/${OMV_BACKUP_FILE_PREFIX}-${date}.fsa" ${devicefile} ${bootpart}${vb} -A -Z ${OMV_BACKUP_FSA_COMP_LEVEL} -j ${threads} ${extra}
    if [ $? -ne 0 ]; then
      _log_error "FSArchiver backup failed!"
      exit 17
    else
      _log "FSArchiver backup complete."
    fi
    touch "${backupDir}/${OMV_BACKUP_FILE_PREFIX}"-${date}.*
    purgeOld
    fsarchiver archinfo ${password} "${backupDir}/${OMV_BACKUP_FILE_PREFIX}-${date}.fsa"
    ;;

  borg)
    _log "Starting borgbackup ..."
    extra=$(omv_config_get "/config/system/backup/extraoptions")
    passwd="$(omv_config_get "/config/system/backup/passwd")"
    if [ -n "${passwd}" ]; then
      _log "Encrypting archive ..."
      export BORG_PASSPHRASE="${passwd}"
    fi
    if [ ! -d "${backupDir}/borgbackup" ] ; then
      # First run - init borg directory
      _log "First run - init borg directory ..."
      if [ -n "${passwd}" ]; then
        borg init -e repokey "${backupDir}/borgbackup"
      else
        borg init -e none "${backupDir}/borgbackup"
      fi
    fi
    _log "Starting borgbackup create ..."
    borg create --stats "${backupDir}/borgbackup::${OMV_BACKUP_FILE_PREFIX}-${date}" / \
      -x --exclude-caches \
      -e "/dev" -e "/proc" -e "/sys" -e "/tmp" -e "/run" -e "/mnt" \
      -e "/media" -e "/lost+found" -e "/export" -e "/home/ftp" -e "/srv" ${extra}
    if [ $? -ne 0 ]; then
      _log_error "borgbackup create failed!"
      exit 18
    else
      _log "borgbackup create complete."
    fi
    keep=$(omv_config_get "/config/system/backup/keep")
    if [[ ${keep} -gt 0 ]]; then
      purgeOld
      _log "Starting borgbackup prune ..."
      borg prune "${backupDir}/borgbackup" --keep-daily "${keep}"
      if [ $? -ne 0 ]; then
        _log_error "borgbackup prune failed!"
        exit 19
      else
        _log "borgbackup prune complete."
      fi
    fi
    ;;

  rsync)
    # add progress flag if verbose is enabled
    vb=""
    if [ ${verbose} -eq 1 ]; then
      vb="v"
    fi
    _log "Starting rsync ..."
    extra=$(omv_config_get "/config/system/backup/extraoptions")

    rsync -aAX${vb}xx /* "${backupDir}/" \
      --delete \
      --exclude=/dev \
      --exclude=/proc \
      --exclude=/sys \
      --exclude=/tmp \
      --exclude=/run \
      --exclude=/mnt \
      --exclude=/media \
      --exclude=/lost+found \
      --exclude=/export \
      --exclude=/home/ftp \
      --exclude=/srv ${extra}
    if [ $? -ne 0 ]; then
      _log_error "rsync backup failed!"
      exit 20
    else
      _log "rsync backup complete."
    fi
    purgeOld
    ;;
esac

_log "Backup complete."

exit 0
