#!/bin/bash

# filename: /etc/keepalived/cron_rsync.sh

run_user="root"
cron_file=/var/spool/cron/$run_user

cron_title='#Keepalived: cron_rsync'
cron_command='/etc/keepalived/cron_rsync.sh run'

add() {
    if test ! "`grep "$cron_title" "$cron_file"`"; then
        echo "$cron_title" >> $cron_file
    fi
    if test ! "`grep "$cron_command" "$cron_file"`"; then
        sed -i "/$cron_title/a */3 * * * * $cron_command" "$cron_file"
    fi
}

del() {
    if test "`grep "$cron_title" "$cron_file"`"; then
        sed -i "/$cron_title/d" "$cron_file"
    fi
    if test "`grep "$cron_command" "$cron_file"`"; then
        sed -i "\#$cron_command#d" "$cron_file"
    fi
}

run() {

    # 定义同步的源目录

    SRC_DIR=/data/nfs/

    # 定义同步的目标目录

    DESC_DIR=/data/nfs

    # 定义所有的ip地址,加入iplist数组
    iplist[0]=172.22.31.101
    iplist[1]=172.22.31.102
    iplist[2]=10.10.88.104
    iplist[3]=172.21.10.71
    iplist[4]=172.21.10.72

    # 取本机的ip地址,只取第一块网卡的。

    local_ip=`/sbin/ifconfig | grep "inet addr" | awk '{print $2}' | awk -F":" 'NR==1{print $2}' | grep -Ev '127.0.0.1'`
    # 从地址的数组里排除本机的地址,开始for循环
    for rsync_ip in ${iplist[@]/$local_ip/}
    do
        # 对这些地址开始rsync同步

        /usr/bin/rsync -vzrtopg --delete $SRC_DIR root@$rsync_ip:$DESC_DIR > /dev/null 2>&1

    done
}

case $1 in
    add)
        add
        ;;
    del)
        del
        ;;
    run)
        run
        ;;
    *)
        echo "$0 (add|del|run)"
esac