#!/bin/sh

## General variables. Modify them as you need
chatid="xxxxxxxxxxxxxxxxx" #chatid is telegram chatid to send notifications
api="xxxxxxxxxxxxxxxxxxxxxxxxxx" #api is telegram bot's token.
## healthcheck="XXXXXXXXXXXX" #Healthcheck is healthchecks.io's API.
log="/remote_logs/borg.log"


# Setting this, so the repo does not need to be given on the commandline:
export BORG_REPO=/bkp-to/

# See the section "Passphrase notes" for more infos.
export BORG_PASSPHRASE='lauqehayaselegido' #la que pusiste en la terminal

## Set current Date
datelog=`date +%Y-%m-%d`
echo "iniciando backup con fecha: $datelog" >> $log

# some helpers and error handling:
info() { printf "\n%s %s\n\n" "$( date )" "$*" >&2; }
trap 'echo $( date ) Backup interrupted >&2; exit 2' INT TERM

# Time count start
timestart=`date +%s`

info "Starting backup"

# Notification to Telegram (Start Backup)
curl -s \
  --data parse_mode=HTML \
  --data chat_id=$chatid \
  --data text="<b>Borg Backup</b>%0A    <i>Repo:</i> Unraid%0A    <i>Tarea:</i> <b>Backup</b>%0A    <i>Estado:</i> Iniciando Backup" \
  "https://api.telegram.org/bot$api/sendMessage"

# Backup the most important directories into an archive named after
# the machine this script is currently running on:

borg create                         \
    --verbose                       \
    --filter AME                    \
    --list                          \
    --stats                         \
    --show-rc                       \
    --compression lz4               \
    --exclude-caches                \
    --exclude 'home/*/.cache/*'     \
    --exclude 'var/tmp/*'           \
    --files-cache ctime,size        \
                                    \
    ::'unraid-{now}'                \
    /bkp-from/videos-canal          \
    /bkp-from/Fotos/                \
    /bkp-from/immich/               \
    /bkp-from/Rosa/                 \
    /bkp-from/comics/               \
    /bkp-from/appdata/              \
    2>> $log


backup_exit=$?

if [ $backup_exit -eq 0 ]; then backup_re="Backup correcto"
elif [ $backup_exit -eq 1 ]; then backup_re="Backup completado pero con advertencias"
else backup_re="ERROR EN BACKUP"
fi



info "Pruning repository"

# Use the `prune` subcommand to maintain 7 daily, 4 weekly and 6 monthly
# archives of THIS machine. The '{hostname}-*' matching is very important to
# limit prune's operation to this machine's archives and not apply to
# other machines' archives also:

borg prune                          \
    --list                          \
    --glob-archives 'unraid-*'      \
    --show-rc                       \
    --keep-daily    7               \
    --keep-weekly   4               \
    --keep-monthly  3

prune_exit=$?

# actually free repo disk space by compacting segments

if [ $prune_exit -eq 0 ]; then prune_re="Prune correcto"
elif [ $prune_exit -eq 1 ]; then prune_re="Prune completado pero con advertencias"
else prune_re="ERROR EN PRUNE"
fi

info "Compacting repository"

borg compact

compact_exit=$?

if [ $compact_exit -eq 0 ]; then compact_re="Compact correcto"
elif [ $compact_exit -eq 1 ]; then compact_re="Compact completado pero con advertencias"
else compact_re="ERROR EN COMPACT"
fi

# use highest exit code as global exit code
global_exit=$(( backup_exit > prune_exit ? backup_exit : prune_exit ))
global_exit=$(( compact_exit > global_exit ? compact_exit : global_exit ))

if [ ${global_exit} -eq 0 ]; then
    info "Backup and Prune finished successfully" >> $log
elif [ ${global_exit} -eq 1 ]; then
    info "Backup and/or Prune finished with warnings" >> $log
else
    info "Backup and/or Prune finished with errors" >> $log
fi


# Time count stop
timestop=`date +%s`
# Total execution time (in seconds)
runtime=$(( timestop - timestart ))
# Total execution time conversion
D=$((runtime/60/60/24))
H=$((runtime/60/60%24))
M=$((runtime/60%60))
S=$((runtime%60))
totaltime="${D}d, ${H}h, ${M}m, ${S}s"

# Calculating disk used and formatting
DATA=$(df /bkp-to -h | awk '{print $3"/"$2" ("$5")"}' | sed -n '2p' | sed 's/T/TB/g; s/G/GB/g; s/M/MB/g')

# Notification to Telegram (End Backup + Send Log)
curl -s \
  --data parse_mode=HTML \
  --data chat_id=$chatid \
  --data text="<b>Borg Backup</b>%0A    <i>Repo:</i> Unraid%0A    <i>Tarea:</i> <b>Backup</b>%0A    <i>Tiempo total:</i>$totaltime%0A   <i>Tamaño de la copia:</i>$DATA%0A  <i>Estado:</i> $backup_re , $prune_re , $compact_re" \
  "https://api.telegram.org/bot$api/sendMessage"



exit ${global_exit}
