#!/bin/sh

[[ "$ACTION" == "ifup" && $(uci get "passwall2.@global[0].enabled") == "1" ]] && [ -f /var/lock/passwall2_ready.lock ] && {
	default_device=$(ip route | grep default | awk -F 'dev ' '{print $2}' | awk '{print $1}')
	[ "$default_device" == "$DEVICE" ] && {
		LOCK_FILE_DIR=/var/lock
		[ ! -d ${LOCK_FILE_DIR} ] && mkdir -p ${LOCK_FILE_DIR}
		LOCK_FILE="${LOCK_FILE_DIR}/passwall2_ifup.lock"
		if [ -s ${LOCK_FILE} ]; then
			SPID=$(cat ${LOCK_FILE})
			if [ -e /proc/${SPID}/status ]; then
				exit 1
			fi
			cat /dev/null > ${LOCK_FILE}
		fi
		echo $$ > ${LOCK_FILE}
		
		/etc/init.d/passwall2 restart >/dev/null 2>&1 &
		echo "passwall2: restart when $INTERFACE ifup" > /dev/kmsg
		
		rm -rf ${LOCK_FILE}
	}
}
