#!/bin/bash

NOW=$(date +%Y%m%d%H%M)
YESTERDAY=$(date -d -1day +%Y%m%d)

### 配置备份系统文件结构 ###
BACKUP_HOME="/srv/backups"    # 备份系统根路径

CURRENT_LINK="$BACKUP_HOME/current"
SNAPSHOT_DIR="$BACKUP_HOME/snapshots"
ARCHIVES_DIR="$BACKUP_HOME/archives"


### 要备份的文件夹 ###
BACKUP_SOURCE_DIR="/etc"


### 创建文件架构 ###
mkdir -p $SNAPSHOT_DIR  $ARCHIVES_DIR &> /dev/null

### 使用rsync进行备份 ###
rsync -azH --link-dest=$CURRENT_LINK  $BACKUP_SOURCE_DIR $SNAPSHOT_DIR/$NOW \
  && ln -snf $(ls -1d $SNAPSHOT_DIR/* | tail -n1) $CURRENT_LINK

### 归档 ###
# 如果快照是昨天的,那就将它压缩归档 
if [ $(ls -d $SNAPSHOT_DIR/$YESTERDAY* 2> /dev/null | wc -l) != "0" ]
then
  tar -czf $ARCHIVES_DIR/$YESTERDAY.tar.gz $SNAPSHOT_DIR/$YESTERDAY* \
    && rm -rf $SNAPSHOT_DIR/$YESTERDAY*
fi

