#!/bin/sh

# PROVIDE: sc_protect
# REQUIRE: NETWORKING DAEMON LOGIN FILESYSTEMS SERVERS
# KEYWORD: nojail

#  $Id: scprotect,v 1.5 2009/11/16 11:55:24 dindin Exp $

. /etc/rc.subr

name="scprotect"
rcvar=`set_rcvar`
load_rc_config $name
: ${scprotect_pid="/var/run/$name.pid"}
: ${sprotect_sleep="300"}

kmod_dir="/boot/modules"

protect_isrunning (){
    if [ -f "${scprotect_pid}" ] && [ -n "$(cat ${scprotect_pid})" ];
    then
        pid="$(cat ${scprotect_pid})"
        if [ -n "$(ps ax -o pid,command | grep $name)" ];then
            return 0
        else
            return 1
        fi
    fi
    return 1
}

protect_cycle() {
    if ! protect_isrunning; then
        echo "Starting $name."
        tmpdir=$(/usr/bin/mktemp -d -t $name)
        # some special magic for view running process as "scprotect",
        # not /etc/rc autoboot

        cat >> ${tmpdir}/$name <<EOF
#!/bin/sh
load_module(){
    if kldstat -m '${name}' > /dev/null 2>&1 ; then
        return 0;
    fi;
    if /sbin/kldload '${kmod_dir}/${name}.ko' ; then
       return 0;
    else 
       return 1;
    fi;
}
protect() {
    for prg in ${scprotect_progs};do
        for path in ${local_startup} /etc/rc.d/; do
            script="\$(realpath \${path}/\${prg})";
            if [ -f "\${script}" ] && [ -x "\${script}" ];
            then
                pid=\$(\$script status | \
                awk '\$2 ~ /is/, \$3 ~ /running/ {print( \$6 )}' | \
                sed -e 's/\.\$//';)
                if [ -n "\${pid}" ]; then
                  /sbin/sysctl ${name}.protect=\${pid} \
                   > /dev/null 2>&1;
                fi;
                break;
            fi;
        done;
    done;
}
while true;do
    if load_module ; then
        protect
    fi
    /bin/sleep ${sprotect_sleep}
done
EOF
    /bin/chmod +x ${tmpdir}/${name}
    cd $tmpdir
    ./${name} &
    echo $! > ${scprotect_pid}
    /bin/rm -Rf ${tmpdir}
fi
}

scprotect_stop() {
    if protect_isrunning ;
    then
        echo "Stopping $name."
        /bin/kill "$(cat ${scprotect_pid})"
        rm ${scprotect_pid}
    fi
}

start_cmd="protect_cycle"
stop_cmd="scprotect_stop"

run_rc_command "$1"
