#!/bin/bash

# Exit on error
set -euo pipefail

## Variables
LOGFILE="/home/alarm/backup/backup.log"
MACHINE_IP="192.168.178.67"

BKP_PATH="/home/alarm/backup/dump/"
MACHINE_PATH="${BKP_PATH}machine/"
HOME_PATH="${MACHINE_PATH}home/"


## Check if backup already ran today
SEC_SINCE_BKP=$(($(date +%s) - $(date +%s -r $LOGFILE)))
HOURS_SINCE_BKP=$((SEC_SINCE_BKP/3600))
if [ "$HOURS_SINCE_BKP" -le 24 ]; then
  exit 0
fi

## Check if machine is up
if ! ping -c 1 -W 3 "$MACHINE_IP" &>/dev/null; then
  exit 0
fi
  

## Backup machine
# Home Dir
echo "[INFO] $(date --rfc-3339 s) - Syncing machine:/home/vashqlf/..."
HOME_TARGETS=(
  "Code"
  ".config"
  "Documents"
  "Pictures"
  ".profile"
  ".ssh"
  ".xprofile"
  ".Xresources"
  ".zshenv"
  ".zshrc"
  )

for i in "${HOME_TARGETS[@]}"; do
  rsync -avP "machine:/home/vashqlf/${i}" "${HOME_PATH}"
done
echo "[INFO] $(date --rfc-3339 s) - Done!"

## Backup cloud hosts
# Strato1: vaultwarden
echo "[INFO] $(date --rfc-3339 s) - Syncing strato1:/home/pw-manager/vaultwarden..."
rsync -avP "strato1:/home/pw-manager/vaultwarden" "${BKP_PATH}"
echo "[INFO] $(date --rfc-3339 s) - Done!"

# Strato3: Checkmk
echo "[INFO] $(date --rfc-3339 s) - Syncing strato3:/usr/local/share/cmk-bkp..."
rsync -avP "strato3:/usr/local/share/cmk-bkp" "${BKP_PATH}"
echo "[INFO] $(date --rfc-3339 s) - Done!"

echo "[INFO] $(date --rfc-3339 s) - Syncing completed, nothing more to do."





