#!/bin/sh /etc/rc.common
# Copyright (C) 2014 OpenWrt.org

START=10
USE_PROCD=1

validate_system_section()
{
    uci_load_validate system system "$1" "$2" \
        'hostname:string:OpenWrt' \
        'conloglevel:uinteger' \
        'log_size:string' \
        'log_file_count:uinteger' \
        'log_file:string' \
        'log_ip:string' \
        'log_port:string' \
        'buffersize:uinteger' \
        'timezone:string:UTC' \
        'zonename:string'
}

system_config() {
    [ "$2" = 0 ] || {
        echo "validation failed"
        return 1
    }

    echo "$hostname" > /proc/sys/kernel/hostname
    [ -z "$conloglevel" -a -z "$buffersize" ] || dmesg ${conloglevel:+-n $conloglevel} ${buffersize:+-s $buffersize}

    if [ "$log_file" != "" ]; then
        mkdir -p `dirname $log_file`
    fi
    procd_open_instance
        procd_set_param command "syslogd"
        procd_append_param command -t -n -C512 ${log_size:+-s ${log_size}} ${log_ip:+-L -R ${log_ip}:${log_port}} ${conloglevel:+-l $(( $conloglevel ))} ${log_file:+-O ${log_file} ${log_file_count:+-b ${log_file_count}}}
        procd_set_param respawn 5 1 -1
    procd_close_instance
    #runtime change log level of components
    sysloglevel=$((conloglevel-1))
    if [[ $sysloglevel -lt 0 ]]; then
        sysloglevel=0
    fi
    for x in `logadm -l | grep '^[a-z]'`; do
        logadm -s $sysloglevel $x
    done

    echo "$timezone" > /tmp/TZ
    [ -n "$zonename" ] && [ -f "/usr/share/zoneinfo/$zonename" ] && \
        ln -sf "/usr/share/zoneinfo/$zonename" /tmp/localtime && rm -f /tmp/TZ

    /bin/mount -o noatime -t pstore pstore /sys/fs/pstore
	if [ -f "/sys/fs/pstore/dmesg-ramoops-0" ]; then
		if grep -q "Kernel panic" "/sys/fs/pstore/console-ramoops-0"; then
			cp /sys/fs/pstore/dmesg-ramoops-0 /tmp/crash.txt
			touch /etc/rebootcause/reboot_panic
			echo "System rebooted due to unexpected error at " `date` > /etc/rebootcause/reboot_panic
		fi
	fi

#    # apply timezone to kernel
#    date -k
}

start_service() {
    config_load system
    config_foreach validate_system_section system system_config
}

service_triggers()
{
    procd_add_reload_trigger "system"
    procd_add_validation validate_system_section
}
