#!/bin/sh
. /lib/functions.sh

apply_config() {
	config_get init "$1" init
	config_get exec "$1" exec
	config_get test "$1" test

	echo "$2" > "/var/run/luci-reload-status"

	### SEANO ###
	[ -f /usr/sbin/email.sh ] && email.sh send_config_changes

	[ -n "$init" ] && reload_init "$2" "$init" "$test"
	[ -n "$exec" ] && reload_exec "$2" "$exec" "$test"
}

reload_exec() {
	local service="$1"
	local ok="$3"
	set -- $2
	local cmd="$1"; shift

	[ -x "$cmd" ] && {
		echo "Reloading $service... "
		( $cmd "$@" ) 2>/dev/null 1>&2
		[ -n "$ok" -a "$?" != "$ok" ] && echo '!!! Failed to reload' $service '!!!'
	}
}

reload_init() {
	[ -x /etc/init.d/$2 ] && /etc/init.d/$2 enabled && {
		[ -f /tmp/init-boot-status ] && {
			grep -q $1 /tmp/init-boot-status || return
		}
		echo "Reloading $1... "
		/etc/init.d/$2 reload >/dev/null 2>&1
		[ -n "$3" -a "$?" != "$3" ] && echo '!!! Failed to reload' $1 '!!!'
	}
}

get_affected() {
lua - <<LUA_END
#!/usr/bin/lua
  local uci = require("luci.model.uci").cursor()
  local os  = require "os"
  local configlist={}
  local string="$*"
  if string=="" then
    changes = uci:changes()
    for _, v in pairs(changes) do
        table.insert(configlist,_)
    end
  else
    string:gsub("[^%s]+",function(c) table.insert(configlist,c) end)
  end
  local affect
  affect=uci:_affected(configlist)
-- table.foreach(affect, function(i, v) uci:commit(v) end)
  os.execute("echo "..table.concat(affect, " ").."")
LUA_END
}

# reorder by config order of ucitrack
sort_list() {
	local order_list=""
	for section in ${CONFIG_SECTIONS}; do
		config_get cfgtype "$section" TYPE
		order_list=$order_list"$cfgtype "
	done
	input=$*

	# filter duplicate config after add force_reload config.
	input=$(echo "$input" | tr ' ' '\n' | sort -u | tr '\n' ' ')

	reload_cases="prereload none postreload"
	rm ${config_priority_sort_file} 2>/dev/null

	# sort with reload_order and ucitrack order_list
	# prereload priority : 0   ~ 99,  if no priority, assign: 50 ~
	# none priority      : 100 ~ 199, if no priority, assign: 150 ~
	# postreload priority: 200 ~ 299, if no priority, assign: 250 ~

	# -50+100 => 50, +100 => 150, +100 => 250
	default_priority="-50"
	priority_count="0"
	input_with_priority=""
	for reload_case in ${reload_cases};do
		default_priority=$((default_priority+100))
		priority_count=$default_priority
		for i in $order_list;do
			for j in $input;do
				[ "$i" = "$j" ] && {
					reload_order=$(uci get ucitrack.@${i}[0].reload_order 2>/dev/null)
					reload_order="${reload_order:-none}"
					if [ "$reload_order" = "$reload_case" ]; then
						priority=$(uci get ucitrack.@${i}[0].priority 2>/dev/null)
						if [ "$priority" = "" ]; then
							priority="$priority_count"
							priority_count=$((priority_count+1))
						fi
						input_with_priority="${input_with_priority} ${priority},$i"
						#echo ${priority},$i >> ${config_priority_sort_file}
					fi
				}
			done
		done
	done

	# sort with priority value
	input=$(echo "$input_with_priority" | tr ' ' '\n' | sort | awk -F ',' '{print $2}' | tr '\n' ' ')

	echo ${input}
}

### SENAO
[ -n "`uci changes`" ] && {
    [ -f "/sbin/senao_check.sh" ] && sh /sbin/senao_check.sh
}
###

if [ "$1" = "auto" ]; then
    isauto=1
    shift
    input=$(get_affected "$*")

    # add forcereload at end of input list
    forcereload=$(uci show ucitrack | grep "forcereload='1'" | awk -F '@' '{print $2}' | awk -F '[' '{print $1}' | tr '\r\n' ' ')
    input=${input}" "${forcereload}

    for i in $input; do
        uci commit $i 2>/dev/null
    done
else
    isauto=0
    input=$*
fi
echo $input
reload_tmp_file="/tmp/reload"

[ "`pgrep -f 'lock /var/run/luci-reload'`" = "" ] || {
    [ $isauto -eq 1 ] && {
        touch $reload_tmp_file 
        for j in $input; do
            grep -q $j $reload_tmp_file || {
                printf " $j" >> $reload_tmp_file
            }
        done
        exit
    } 
}

lock "/var/run/luci-reload"
config_load ucitrack

input=$(sort_list $input)
while [ -n "$input" ]
do
    for i in $input; do
        config_foreach apply_config $i $i
    done
    [ -s $reload_tmp_file ] && {
        input=$(sort_list $(cat $reload_tmp_file 2>/dev/null))
        rm -f $reload_tmp_file
    } || {
        input=""
    }
done

if [ -e "/usr/sbin/print_change_log.sh" ]; then
	if [ -e "/tmp/logger_channel_change" ]; then
		rm -f /tmp/logger_channel_change
		change_ch=`uci get wireless.wifi1.channel`
		[ -n "$change_ch" ] && {
#			echo "luci-reload logger [$change_ch] to logger" > /dev/console
			logger "modify wifi1 channel to $change_ch" -t channel -p 5
		}
	fi
fi

rm -f "/var/run/luci-reload-status"
lock -u "/var/run/luci-reload"

