#!/bin/bash
#引用函数库
[ -f /etc/init.d/functions ] && source /etc/init.d/functions
#判断执行脚本是否存在位置变量
if [ $# -ne 1 ];then
    echo "Usage: $0 {start|stop|status|restart}"
    exit
fi
#根据位置变量的结果进行执行相对应的命令
Pid_File=/var/run/rsync.pid
case $1 in
    start)
        if [ -f $Pid_File ];then
            action "服务Rsync正在运行中......"  /bin/true
        else
            #启动服务
            /usr/bin/rsync --daemon &>/dev/null && sleep 2
            if [ $? -eq 0 ];then
                action "服务Rsync启动成功......" /bin/true
                Pid=$(ps aux | grep  rsync |  awk 'NR==1{print $2}')
                echo $Pid  >$Pid_File
            else
                action "服务Rsync启动失败......" /bin/false
                exit
            fi

        fi
        ;;
    stop)
        if [ -f $Pid_File ];then
            pkill rsync &>/dev/null && sleep 2
            if [ $? -eq 0 ];then
                action "服务Rsync停止成功......" /bin/true
                rm -f $Pid_File &>/dev/null
            else
                action "服务Rsync停止失败......" /bin/false
            fi
        else
            action "服务Rsync不在运行中......"  /bin/true
        fi
        ;;
    status)
        if [ -f $Pid_File ];then
            action "服务Rsync正在运行中......"  /bin/true
        else
            action "服务Rsync不在运行中......"  /bin/true
        fi
        ;;
    restart)
        if [ -f $Pid_File ];then
            #先停止服务
            pkill rsync &>/dev/null && sleep 2
            if [ $? -eq 0 ];then
                action "服务Rsync停止成功......" /bin/true
                rm -f $Pid_File &>/dev/null
            else
                action "服务Rsync停止失败......" /bin/false
            fi
            #再启动服务
            /usr/bin/rsync --daemon &>/dev/null && sleep 2
            if [ $? -eq 0 ];then
                action "服务Rsync启动成功......" /bin/true
                Pid=$(ps aux | grep  rsync |  awk 'NR==1{print $2}')
                echo $Pid  >$Pid_File
            else
                action "服务Rsync启动失败......" /bin/false
                exit
            fi
        else
            action "服务Rsync不在运行中......"  /bin/true
            #直接启动
            /usr/bin/rsync --daemon &>/dev/null && sleep 2
            if [ $? -eq 0 ];then
                action "服务Rsync启动成功......" /bin/true
                Pid=$(ps aux | grep  rsync |  awk 'NR==1{print $2}')
                echo $Pid  >$Pid_File
            else
                action "服务Rsync启动失败......" /bin/false
                exit
            fi
        fi
        ;;
    *)
        echo "Usage: $0 {start|stop|status|restart}"
        exit
esac