#!/bin/sh

PATH=/usr/local/bin:/usr/bin:/bin

# --- CONFIGURATION ---
REPO="sftp:anto@192.168.1.168:/media/anto/Maxtor/restic-backup"
BACKUP_PATH="/mnt"
PASSWORD_FILE="/root/.restic_pass"
DISCORD_WEBHOOK="https://discord.com/api/webhooks/1483223739494830233/3b9BOJh27jAGB9tKhslInnSpBngIg_4cedC1s5s5D1bvL-u_Rw3EMm3U6CEkkFY2fNo5"

export RESTIC_PASSWORD_FILE=$PASSWORD_FILE

# --- Fonction notification Discord ---
send_discord() {
    MESSAGE=$(printf "%s" "$1" | tr '\n' ' ' | sed 's/"/\\"/g' | cut -c1-1800)

    /usr/local/bin/curl -s -o /tmp/discord_status.txt -w "%{http_code}" \
    -H "Content-Type: application/json" \
    -d "{\"content\":\"$MESSAGE\"}" \
    "$DISCORD_WEBHOOK"
}


HOST=$(hostname)
DATE=$(date)

send_discord "**Backup restic démarrée** sur **$HOST** à $DATE"
echo "Discord HTTP status: $(cat /tmp/discord_status.txt)"
LOG=$(mktemp)

# --- BACKUP ---
restic -r $REPO backup $BACKUP_PATH 2>&1 | tee $LOG
STATUS=$?

# --- RETENTION ---
restic -r $REPO forget --keep-daily 7 --keep-weekly 4 --keep-monthly 12 >> $LOG 2>&1
restic -r $REPO prune >> $LOG 2>&1

# --- STATS ---
SUMMARY=$(grep -E "Files:|Added to the repository|processed|snapshot" $LOG)
SUMMARY=$(echo "$SUMMARY" | tr '\n' ' ' | cut -c1-1500)

send_discord "✅ **Backup réussie sur $HOST**

📦 Résumé:
$SUMMARY"
