View difference between Paste ID: DHb2JhqH and 9hkbU3Mf
SHOW: | | - or go back to the newest paste.
1
#!/bin/sh
2
3
FILE_TO_WATCH="/tmp/ndnproxymain.conf"
4-
PREVIOUS_HASH=""
4+
HASH_FILE="/var/run/ipset_watcher.hash"
5
6
# Commands to execute when the file changes
7
COMMANDS_ON_CHANGE="
8
    ipset flush bypass
9-
    /opt/etc/init.d/S52ipset-dns restart
9+
10
11
# Function to calculate MD5 hash of the file
12
calculate_md5() {
13
    md5sum "$FILE_TO_WATCH" | awk '{ print $1 }'
14
}
15
16
# Function to execute commands when the file changes
17
on_file_change() {
18
    eval "$COMMANDS_ON_CHANGE"
19
}
20
21
# Function to start the script
22
start() {
23
    # Load previous hash from file if it exists
24-
    echo "Starting ipset watcher..."
24+
    if [ -f "$HASH_FILE" ]; then
25-
    PREVIOUS_HASH=$(calculate_md5)
25+
        PREVIOUS_HASH=$(cat "$HASH_FILE")
26-
    inotifywait -q -m -e close_write "$FILE_TO_WATCH" | while read _; do
26+
    else
27
        PREVIOUS_HASH=$(calculate_md5)
28
        echo "$PREVIOUS_HASH" > "$HASH_FILE"
29
    fi
30
31
    # Monitor the file for changes
32
    inotifywait -q -m -e modify,attrib,close_write "$FILE_TO_WATCH" | while read; do
33
        CURRENT_HASH=$(calculate_md5)
34
        if [ "$CURRENT_HASH" != "$PREVIOUS_HASH" ]; then
35
            PREVIOUS_HASH="$CURRENT_HASH"
36
            echo "$PREVIOUS_HASH" > "$HASH_FILE"
37
            on_file_change
38-
    echo "Stopping ipset watcher..."
38+
39-
    kill $(cat /var/run/ipset_watcher.pid)
39+
40-
    rm /var/run/ipset_watcher.pid
40+
41
}
42
43
# Function to stop the script
44
45
stop() {
46
    if [ -f /var/run/ipset_watcher.pid ]; then
47
        PID=$(cat /var/run/ipset_watcher.pid)
48
        kill "$PID"
49
        sleep 1
50
        if ps -p "$PID" > /dev/null; then
51
            echo "Process $PID still running, sending SIGKILL"
52
            kill -9 "$PID"
53
        fi
54
        rm /var/run/ipset_watcher.pid
55-
        echo "Usage: $0 {start|stop|restart}"
55+
    else
56
    # Use killall as a fallback
57
    killall inotifywait
58
    fi
59
}
60
61
# Function to check the status of the script
62
status() {
63
    if [ -f /var/run/ipset_watcher.pid ]; then
64
        PID=$(cat /var/run/ipset_watcher.pid)
65
        
66
        # Check if the PID is in the ps output
67
        if ps | grep -w "$PID" | grep -v grep > /dev/null; then
68
            echo "Monitoring process is running (PID: $PID)."
69
        else
70
            echo "Monitoring process not running, but PID file exists."
71
        fi
72
    else
73
        echo "Monitoring process is not running."
74
    fi
75
}
76
77
case "$1" in
78
    start)
79
        start
80
        ;;
81
    stop)
82
        stop
83
        ;;
84
    restart)
85
        stop
86
        start
87
        ;;
88
    status)
89
        status
90
        ;;
91
    *)
92
        echo "Usage: $0 {start|stop|restart|status}"
93
        exit 1
94
        ;;
95
esac
96
97
exit 0
98