ASR_BASE

Change-Id: Icf3719cc0afe3eeb3edc7fa80a2eb5199ca9dda1
diff --git a/package/base-files/files/bin/board_detect b/package/base-files/files/bin/board_detect
new file mode 100755
index 0000000..94f45be
--- /dev/null
+++ b/package/base-files/files/bin/board_detect
@@ -0,0 +1,14 @@
+#!/bin/sh
+
+CFG=$1
+
+[ -n "$CFG" ] || CFG=/etc/board.json
+
+[ -d "/etc/board.d/" -a ! -s "$CFG" ] && {
+	for a in $(ls /etc/board.d/*); do
+		[ -s $a ] || continue;
+		$(. $a)
+	done
+}
+
+[ -s "$CFG" ] || return 1
diff --git a/package/base-files/files/bin/config_generate b/package/base-files/files/bin/config_generate
new file mode 100755
index 0000000..a9d8837
--- /dev/null
+++ b/package/base-files/files/bin/config_generate
@@ -0,0 +1,548 @@
+#!/bin/sh
+
+CFG=/etc/board.json
+
+. /usr/share/libubox/jshn.sh
+
+[ -s $CFG ] || /bin/board_detect || exit 1
+[ -s /etc/config/network -a -s /etc/config/system ] && exit 0
+
+generate_bridge() {
+	local name=$1
+	local macaddr=$2
+	uci -q batch <<-EOF
+		set network.$name=device
+		set network.$name.name=$name
+		set network.$name.type=bridge
+	EOF
+	if [ -n "$macaddr" ]; then
+		uci -q batch <<-EOF
+			set network.$name.macaddr=$macaddr
+		EOF
+	fi
+}
+
+bridge_vlan_id=0
+generate_bridge_vlan() {
+	local name=$1_vlan
+	local device=$2
+	local ports="$3"
+	local vlan="$4"
+	uci -q batch <<-EOF
+		set network.$name=bridge-vlan
+		set network.$name.device='$device'
+		set network.$name.vlan='$vlan'
+		set network.$name.ports='$ports'
+	EOF
+}
+
+generate_static_network() {
+	uci -q batch <<-EOF
+		delete network.loopback
+		set network.loopback='interface'
+		set network.loopback.device='lo'
+		set network.loopback.proto='static'
+		set network.loopback.ipaddr='127.0.0.1'
+		set network.loopback.netmask='255.0.0.0'
+	EOF
+		[ -e /proc/sys/net/ipv6 ] && {
+			uci -q batch <<-EOF
+				delete network.globals
+				set network.globals='globals'
+				set network.globals.ula_prefix='auto'
+			EOF
+		}
+
+	if json_is_a dsl object; then
+		json_select dsl
+			if json_is_a atmbridge object; then
+				json_select atmbridge
+					local vpi vci encaps payload nameprefix
+					json_get_vars vpi vci encaps payload nameprefix
+					uci -q batch <<-EOF
+						delete network.atm
+						set network.atm='atm-bridge'
+						set network.atm.vpi='$vpi'
+						set network.atm.vci='$vci'
+						set network.atm.encaps='$encaps'
+						set network.atm.payload='$payload'
+						set network.atm.nameprefix='$nameprefix'
+					EOF
+				json_select ..
+			fi
+
+			if json_is_a modem object; then
+				json_select modem
+					local type annex firmware tone xfer_mode
+					json_get_vars type annex firmware tone xfer_mode
+					uci -q batch <<-EOF
+						delete network.dsl
+						set network.dsl='dsl'
+						set network.dsl.annex='$annex'
+						set network.dsl.firmware='$firmware'
+						set network.dsl.tone='$tone'
+						set network.dsl.xfer_mode='$xfer_mode'
+					EOF
+				json_select ..
+			fi
+		json_select ..
+	fi
+}
+
+addr_offset=2
+generate_network() {
+	local ports device macaddr protocol type ipaddr netmask vlan
+	local bridge=$2
+
+	json_select network
+		json_select "$1"
+			json_get_vars device macaddr metric protocol ipaddr netmask vlan
+			json_get_values ports ports
+		json_select ..
+	json_select ..
+
+	[ -n "$device" -o -n "$ports" ] || return
+
+	# Force bridge for "lan" as it may have other devices (e.g. wireless)
+	# bridged
+	[ "$1" = "lan" -a -z "$ports" ] && {
+		ports="$device"
+	}
+
+	[ -n "$ports" -a -z "$bridge" ] && {
+		uci -q batch <<-EOF
+			add network device
+			set network.@device[-1].name='br-$1'
+			set network.@device[-1].type='bridge'
+		EOF
+		for port in $ports; do uci add_list network.@device[-1].ports="$port"; done
+		[ -n "$macaddr" ] && {
+			for port in $ports; do
+				uci -q batch <<-EOF
+					add network device
+					set network.@device[-1].name='$port'
+					set network.@device[-1].macaddr='$macaddr'
+				EOF
+			done
+		}
+		device=br-$1
+		type=
+		macaddr=""
+	}
+
+	[ -n "$bridge" ] && {
+		[ -z "$ports" ] && ports="$device"
+		if [ -z "$vlan" ]; then
+			bridge_vlan_id=$((bridge_vlan_id + 1))
+			vlan=$bridge_vlan_id
+		fi
+		generate_bridge_vlan $1 $bridge "$ports" $vlan
+		device=$bridge.$vlan
+		type=""
+	}
+
+	if [ -n "$macaddr" ]; then
+		uci -q batch <<-EOF
+			add network device
+			set network.@device[-1].name='$device'
+			set network.@device[-1].macaddr='$macaddr'
+		EOF
+	fi
+
+	uci -q batch <<-EOF
+		delete network.$1
+		set network.$1='interface'
+		set network.$1.type='$type'
+		set network.$1.device='$device'
+		set network.$1.metric='$metric'
+		set network.$1.proto='none'
+	EOF
+
+	case "$protocol" in
+		static)
+			local ipad
+			case "$1" in
+				lan) ipad=${ipaddr:-"192.168.1.1"} ;;
+				*) ipad=${ipaddr:-"192.168.$((addr_offset++)).1"} ;;
+			esac
+
+			netm=${netmask:-"255.255.255.0"}
+
+			uci -q batch <<-EOF
+				set network.$1.proto='static'
+				set network.$1.ipaddr='$ipad'
+				set network.$1.netmask='$netm'
+			EOF
+			[ -e /proc/sys/net/ipv6 ] && uci set network.$1.ip6assign='60'
+		;;
+
+		dhcp)
+			# fixup IPv6 slave interface if parent is a bridge
+			[ "$type" = "bridge" ] && device="br-$1"
+
+			uci set network.$1.proto='dhcp'
+			[ -e /proc/sys/net/ipv6 ] && {
+				uci -q batch <<-EOF
+					delete network.${1}6
+					set network.${1}6='interface'
+					set network.${1}6.device='$device'
+					set network.${1}6.proto='dhcpv6'
+				EOF
+			}
+		;;
+
+		pppoe)
+			uci -q batch <<-EOF
+				set network.$1.proto='pppoe'
+				set network.$1.username='username'
+				set network.$1.password='password'
+			EOF
+			[ -e /proc/sys/net/ipv6 ] && {
+				uci -q batch <<-EOF
+					set network.$1.ipv6='1'
+					delete network.${1}6
+					set network.${1}6='interface'
+					set network.${1}6.device='@${1}'
+					set network.${1}6.proto='dhcpv6'
+				EOF
+			}
+		;;
+
+		ncm|\
+		qmi|\
+		mbim)
+			uci -q batch <<-EOF
+				set network.$1.proto='${protocol}'
+				set network.$1.pdptype='ipv4'
+			EOF
+		;;
+	esac
+}
+
+generate_switch_vlans_ports() {
+	local switch="$1"
+	local port ports role roles num attr val
+
+	#
+	# autogenerate vlans
+	#
+
+	if json_is_a roles array; then
+		json_get_keys roles roles
+		json_select roles
+
+		for role in $roles; do
+			json_select "$role"
+				json_get_vars ports
+			json_select ..
+
+			uci -q batch <<-EOF
+				add network switch_vlan
+				set network.@switch_vlan[-1].device='$switch'
+				set network.@switch_vlan[-1].vlan='$role'
+				set network.@switch_vlan[-1].ports='$ports'
+			EOF
+		done
+
+		json_select ..
+	fi
+
+
+	#
+	# write port specific settings
+	#
+
+	if json_is_a ports array; then
+		json_get_keys ports ports
+		json_select ports
+
+		for port in $ports; do
+			json_select "$port"
+				json_get_vars num
+
+				if json_is_a attr object; then
+					json_get_keys attr attr
+					json_select attr
+						uci -q batch <<-EOF
+							add network switch_port
+							set network.@switch_port[-1].device='$switch'
+							set network.@switch_port[-1].port=$num
+						EOF
+
+						for attr in $attr; do
+							json_get_var val "$attr"
+							uci -q set network.@switch_port[-1].$attr="$val"
+						done
+					json_select ..
+				fi
+			json_select ..
+		done
+
+		json_select ..
+	fi
+}
+
+generate_switch() {
+	local key="$1"
+	local vlans
+
+	json_select switch
+	json_select "$key"
+	json_get_vars enable reset blinkrate cpu_port \
+		ar8xxx_mib_type ar8xxx_mib_poll_interval
+
+	uci -q batch <<-EOF
+		add network switch
+		set network.@switch[-1].name='$key'
+		set network.@switch[-1].reset='$reset'
+		set network.@switch[-1].enable_vlan='$enable'
+		set network.@switch[-1].blinkrate='$blinkrate'
+		set network.@switch[-1].ar8xxx_mib_type='$ar8xxx_mib_type'
+		set network.@switch[-1].ar8xxx_mib_poll_interval='$ar8xxx_mib_poll_interval'
+	EOF
+
+	generate_switch_vlans_ports "$1"
+
+	json_select ..
+	json_select ..
+}
+
+generate_static_system() {
+	uci -q batch <<-EOF
+		delete system.@system[0]
+		add system system
+		set system.@system[-1].hostname='OpenWrt'
+		set system.@system[-1].timezone='CST-8'
+		set system.@system[-1].zonename='Asia/Shanghai'
+		set system.@system[-1].ttylogin='0'
+		set system.@system[-1].log_size='64'
+		set system.@system[-1].urandom_seed='0'
+
+		delete system.ntp
+		set system.ntp='timeserver'
+		set system.ntp.enabled='1'
+		set system.ntp.enable_server='0'
+		add_list system.ntp.server='0.openwrt.pool.ntp.org'
+		add_list system.ntp.server='1.openwrt.pool.ntp.org'
+		add_list system.ntp.server='2.openwrt.pool.ntp.org'
+		add_list system.ntp.server='3.openwrt.pool.ntp.org'
+	EOF
+
+	if json_is_a system object; then
+		json_select system
+			local hostname
+			if json_get_var hostname hostname; then
+				uci -q set "system.@system[-1].hostname=$hostname"
+			fi
+
+			local compat_version
+			if json_get_var compat_version compat_version; then
+				uci -q set "system.@system[-1].compat_version=$compat_version"
+			else
+				uci -q set "system.@system[-1].compat_version=1.0"
+			fi
+
+			local timezone
+			if json_get_var timezone timezone; then
+				uci -q set "system.@system[-1].timezone=$timezone"
+			fi
+
+			if json_is_a ntpserver array; then
+				local keys key
+				json_get_keys keys ntpserver
+				json_select ntpserver
+					uci -q delete "system.ntp.server"
+
+					for key in $keys; do
+						local server
+						if json_get_var server "$key"; then
+							uci -q add_list "system.ntp.server=$server"
+						fi
+					done
+				json_select ..
+			fi
+		json_select ..
+	fi
+}
+
+generate_rssimon() {
+	local key="$1"
+	local cfg="rssid_$key"
+	local refresh threshold
+
+	json_select rssimon
+	json_select "$key"
+	json_get_vars refresh threshold
+	json_select ..
+	json_select ..
+
+	uci -q batch <<-EOF
+		delete system.$cfg
+		set system.$cfg='rssid'
+		set system.$cfg.dev='$key'
+		set system.$cfg.refresh='$refresh'
+		set system.$cfg.threshold='$threshold'
+	EOF
+}
+
+generate_led() {
+	local key="$1"
+	local cfg="led_$key"
+
+	json_select led
+	json_select "$key"
+	json_get_vars name sysfs type trigger default
+
+	uci -q batch <<-EOF
+		delete system.$cfg
+		set system.$cfg='led'
+		set system.$cfg.name='$name'
+		set system.$cfg.sysfs='$sysfs'
+		set system.$cfg.trigger='$trigger'
+		set system.$cfg.default='$default'
+	EOF
+
+	case "$type" in
+		gpio)
+			local gpio inverted
+			json_get_vars gpio inverted
+			uci -q batch <<-EOF
+				set system.$cfg.trigger='gpio'
+				set system.$cfg.gpio='$gpio'
+				set system.$cfg.inverted='$inverted'
+			EOF
+		;;
+
+		netdev)
+			local device mode
+			json_get_vars device mode
+			uci -q batch <<-EOF
+				set system.$cfg.trigger='netdev'
+				set system.$cfg.mode='$mode'
+				set system.$cfg.dev='$device'
+			EOF
+		;;
+
+		usb)
+			local device
+			json_get_vars device
+			uci -q batch <<-EOF
+				set system.$cfg.trigger='usbdev'
+				set system.$cfg.interval='50'
+				set system.$cfg.dev='$device'
+			EOF
+		;;
+
+		usbport)
+			local ports port
+			json_get_values ports ports
+			uci set system.$cfg.trigger='usbport'
+			for port in $ports; do
+				uci add_list system.$cfg.port=$port
+			done
+		;;
+
+		rssi)
+			local iface minq maxq offset factor
+			json_get_vars iface minq maxq offset factor
+			uci -q batch <<-EOF
+				set system.$cfg.trigger='rssi'
+				set system.$cfg.iface='rssid_$iface'
+				set system.$cfg.minq='$minq'
+				set system.$cfg.maxq='$maxq'
+				set system.$cfg.offset='$offset'
+				set system.$cfg.factor='$factor'
+			EOF
+		;;
+
+		switch)
+			local port_mask speed_mask mode
+			json_get_vars port_mask speed_mask mode
+			uci -q batch <<-EOF
+				set system.$cfg.port_mask='$port_mask'
+				set system.$cfg.speed_mask='$speed_mask'
+				set system.$cfg.mode='$mode'
+			EOF
+		;;
+
+		portstate)
+			local port_state
+			json_get_vars port_state
+			uci -q batch <<-EOF
+				set system.$cfg.port_state='$port_state'
+			EOF
+		;;
+
+		timer|oneshot)
+			local delayon delayoff
+			json_get_vars delayon delayoff
+			uci -q batch <<-EOF
+				set system.$cfg.trigger='$type'
+				set system.$cfg.delayon='$delayon'
+				set system.$cfg.delayoff='$delayoff'
+			EOF
+		;;
+	esac
+
+	json_select ..
+	json_select ..
+}
+
+generate_gpioswitch() {
+	local cfg="$1"
+
+	json_select gpioswitch
+		json_select "$cfg"
+			local name pin default
+			json_get_vars name pin default
+			uci -q batch <<-EOF
+				delete system.$cfg
+				set system.$cfg='gpio_switch'
+				set system.$cfg.name='$name'
+				set system.$cfg.gpio_pin='$pin'
+				set system.$cfg.value='$default'
+			EOF
+		json_select ..
+	json_select ..
+}
+
+json_init
+json_load "$(cat ${CFG})"
+
+umask 077
+
+if [ ! -s /etc/config/network ]; then
+	bridge_name=""
+	touch /etc/config/network
+	generate_static_network
+
+	json_get_vars bridge
+	[ -n "$bridge" ] && {
+		json_select bridge
+		json_get_vars name macaddr
+		generate_bridge "$name" "$macaddr"
+		json_select ..
+		bridge_name=$name
+	}
+
+	json_get_keys keys network
+	for key in $keys; do generate_network $key $bridge_name; done
+
+	json_get_keys keys switch
+	for key in $keys; do generate_switch $key; done
+fi
+
+if [ ! -s /etc/config/system ]; then
+	touch /etc/config/system
+	generate_static_system
+
+	json_get_keys keys rssimon
+	for key in $keys; do generate_rssimon $key; done
+
+	json_get_keys keys gpioswitch
+	for key in $keys; do generate_gpioswitch $key; done
+
+	json_get_keys keys led
+	for key in $keys; do generate_led $key; done
+fi
+uci commit
diff --git a/package/base-files/files/bin/ipcalc.sh b/package/base-files/files/bin/ipcalc.sh
new file mode 100755
index 0000000..871a49e
--- /dev/null
+++ b/package/base-files/files/bin/ipcalc.sh
@@ -0,0 +1,143 @@
+#!/bin/sh
+
+. /lib/functions/ipv4.sh
+
+PROG="$(basename "$0")"
+
+# wrapper to convert an integer to an address, unless we're using
+# decimal output format.
+# hook for library function
+_ip2str() {
+    local var="$1" n="$2"
+    assert_uint32 "$n" || exit 1
+
+    if [ "$decimal" -ne 0 ]; then
+	export -- "$var=$n"
+    elif [ "$hexadecimal" -ne 0 ]; then
+	export -- "$var=$(printf "%x" "$n")"
+    else
+        ip2str "$@"
+    fi
+}
+
+usage() {
+    echo "Usage: $PROG [ -d | -x ] address/prefix [ start limit ]" >&2
+    exit 1
+}
+
+decimal=0
+hexadecimal=0
+if [ "$1" = "-d" ]; then
+    decimal=1
+    shift
+elif [ "$1" = "-x" ]; then
+    hexadecimal=1
+    shift
+fi
+
+if [ $# -eq 0 ]; then
+    usage
+fi
+
+case "$1" in
+*/*.*)
+    # data is n.n.n.n/m.m.m.m format, like on a Cisco router
+    str2ip ipaddr "${1%/*}" || exit 1
+    str2ip netmask "${1#*/}" || exit 1
+    netmask2prefix prefix "$netmask" || exit 1
+    shift
+    ;;
+*/*)
+    # more modern prefix notation of n.n.n.n/p
+    str2ip ipaddr "${1%/*}" || exit 1
+    prefix="${1#*/}"
+    assert_uint32 "$prefix" || exit 1
+    if [ "$prefix" -gt 32 ]; then
+	printf "Prefix out of range (%s)\n" "$prefix" >&2
+	exit 1
+    fi
+    prefix2netmask netmask "$prefix" || exit 1
+    shift
+    ;;
+*)
+    # address and netmask as two separate arguments
+    str2ip ipaddr "$1" || exit 1
+    str2ip netmask "$2" || exit 1
+    netmask2prefix prefix "$netmask" || exit 1
+    shift 2
+    ;;
+esac
+
+# we either have no arguments left, or we have a range start and length
+if [ $# -ne 0 ] && [ $# -ne 2 ]; then
+    usage
+fi
+
+# complement of the netmask, i.e. the hostmask
+hostmask=$((netmask ^ 0xffffffff))
+network=$((ipaddr & netmask))
+broadcast=$((network | hostmask))
+count=$((hostmask + 1))
+
+_ip2str IP "$ipaddr"
+_ip2str NETMASK "$netmask"
+_ip2str NETWORK "$network"
+
+echo "IP=$IP"
+echo "NETMASK=$NETMASK"
+# don't include this-network or broadcast addresses
+if [ "$prefix" -le 30 ]; then
+    _ip2str BROADCAST "$broadcast"
+    echo "BROADCAST=$BROADCAST"
+fi
+echo "NETWORK=$NETWORK"
+echo "PREFIX=$prefix"
+echo "COUNT=$count"
+
+# if there's no range, we're done
+[ $# -eq 0 ] && exit 0
+[ -z "$1$2" ] && exit 0
+
+if [ "$prefix" -le 30 ]; then
+    lower=$((network + 1))
+else
+    lower="$network"
+fi
+
+start="$1"
+assert_uint32 "$start" || exit 1
+start=$((network | (start & hostmask)))
+[ "$start" -lt "$lower" ] && start="$lower"
+[ "$start" -eq "$ipaddr" ] && start=$((start + 1))
+
+if [ "$prefix" -le 30 ]; then
+    upper=$(((network | hostmask) - 1))
+elif [ "$prefix" -eq 31 ]; then
+    upper=$((network | hostmask))
+else
+    upper="$network"
+fi
+
+range="$2"
+assert_uint32 "$range" || exit 1
+end=$((start + range - 1))
+[ "$end" -gt "$upper" ] && end="$upper"
+[ "$end" -eq "$ipaddr" ] && end=$((end - 1))
+
+if [ "$start" -gt "$end" ]; then
+    echo "network ($NETWORK/$prefix) too small" >&2
+    exit 1
+fi
+
+_ip2str START "$start"
+_ip2str END "$end"
+
+if [ "$start" -le "$ipaddr" ] && [ "$ipaddr" -le "$end" ]; then
+    echo "error: address $IP inside range $START..$END" >&2
+    exit 1
+fi
+
+echo "START=$START"
+echo "END=$END"
+
+exit 0
diff --git a/package/base-files/files/etc/banner b/package/base-files/files/etc/banner
new file mode 100644
index 0000000..f3af3c0
--- /dev/null
+++ b/package/base-files/files/etc/banner
@@ -0,0 +1,8 @@
+  _______                     ________        __
+ |       |.-----.-----.-----.|  |  |  |.----.|  |_
+ |   -   ||  _  |  -__|     ||  |  |  ||   _||   _|
+ |_______||   __|_____|__|__||________||__|  |____|
+          |__| W I R E L E S S   F R E E D O M
+ -----------------------------------------------------
+ %D %V, %C
+ -----------------------------------------------------
diff --git a/package/base-files/files/etc/banner.failsafe b/package/base-files/files/etc/banner.failsafe
new file mode 100644
index 0000000..49855e7
--- /dev/null
+++ b/package/base-files/files/etc/banner.failsafe
@@ -0,0 +1,15 @@
+================= FAILSAFE MODE active ================
+special commands:
+* firstboot	     reset settings to factory defaults
+* mount_root	 mount root-partition with config files
+
+after mount_root:
+* passwd			 change root's password
+* /etc/config		    directory with config files
+
+for more help see:
+https://openwrt.org/docs/guide-user/troubleshooting/
+- failsafe_and_factory_reset
+- root_password_reset
+=======================================================
+
diff --git a/package/base-files/files/etc/board.d/99-default_network b/package/base-files/files/etc/board.d/99-default_network
new file mode 100644
index 0000000..49d2a3b
--- /dev/null
+++ b/package/base-files/files/etc/board.d/99-default_network
@@ -0,0 +1,16 @@
+#
+# Copyright (C) 2013-2015 OpenWrt.org
+#
+
+. /lib/functions/uci-defaults.sh
+
+board_config_update
+
+json_is_a network object && exit 0
+
+ucidef_set_interface_lan 'eth0'
+[ -d /sys/class/net/eth1 ] && ucidef_set_interface_wan 'eth1'
+
+board_config_flush
+
+exit 0
diff --git a/package/base-files/files/etc/device_info b/package/base-files/files/etc/device_info
new file mode 100644
index 0000000..4045e9e
--- /dev/null
+++ b/package/base-files/files/etc/device_info
@@ -0,0 +1,4 @@
+DEVICE_MANUFACTURER='%M'
+DEVICE_MANUFACTURER_URL='%m'
+DEVICE_PRODUCT='%P'
+DEVICE_REVISION='%h'
diff --git a/package/base-files/files/etc/diag.sh b/package/base-files/files/etc/diag.sh
new file mode 100644
index 0000000..37a8ec7
--- /dev/null
+++ b/package/base-files/files/etc/diag.sh
@@ -0,0 +1,52 @@
+#!/bin/sh
+# Copyright (C) 2006-2019 OpenWrt.org
+
+. /lib/functions/leds.sh
+
+boot="$(get_dt_led boot)"
+failsafe="$(get_dt_led failsafe)"
+running="$(get_dt_led running)"
+upgrade="$(get_dt_led upgrade)"
+
+set_led_state() {
+	status_led="$boot"
+
+	case "$1" in
+	preinit)
+		status_led_blink_preinit
+		;;
+	failsafe)
+		status_led_off
+		[ -n "$running" ] && {
+			status_led="$running"
+			status_led_off
+		}
+		status_led="$failsafe"
+		status_led_blink_failsafe
+		;;
+	preinit_regular)
+		status_led_blink_preinit_regular
+		;;
+	upgrade)
+		[ -n "$running" ] && {
+			status_led="$running"
+			status_led_off
+		}
+		status_led="$upgrade"
+		status_led_blink_preinit_regular
+		;;
+	done)
+		status_led_off
+		[ "$status_led" != "$running" ] && \
+			status_led_restore_trigger "boot"
+		[ -n "$running" ] && {
+			status_led="$running"
+			status_led_on
+		}
+		;;
+	esac
+}
+
+set_state() {
+	[ -n "$boot" -o -n "$failsafe" -o -n "$running" -o -n "$upgrade" ] && set_led_state "$1"
+}
diff --git a/package/base-files/files/etc/ethers b/package/base-files/files/etc/ethers
new file mode 100644
index 0000000..b92c200
--- /dev/null
+++ b/package/base-files/files/etc/ethers
@@ -0,0 +1,6 @@
+#
+#  Lookup man 5 ethers for syntax documentation
+#
+#  Examples :
+#	02:00:11:22:33:44	OpenWrt.lan
+#	02:00:11:22:33:44	192.168.1.1
diff --git a/package/base-files/files/etc/fstab b/package/base-files/files/etc/fstab
new file mode 100644
index 0000000..6e9b7ba
--- /dev/null
+++ b/package/base-files/files/etc/fstab
@@ -0,0 +1 @@
+# <file system> <mount point> <type> <options> <dump> <pass>
diff --git a/package/base-files/files/etc/group b/package/base-files/files/etc/group
new file mode 100644
index 0000000..5b06dc6
--- /dev/null
+++ b/package/base-files/files/etc/group
@@ -0,0 +1,11 @@
+root:x:0:
+daemon:x:1:
+adm:x:4:
+mail:x:8:
+dialout:x:20:
+audio:x:29:
+www-data:x:33:
+ftp:x:55:
+users:x:100:
+network:x:101:
+nogroup:x:65534:
diff --git a/package/base-files/files/etc/hosts b/package/base-files/files/etc/hosts
new file mode 100644
index 0000000..b7713eb
--- /dev/null
+++ b/package/base-files/files/etc/hosts
@@ -0,0 +1,5 @@
+127.0.0.1 localhost
+
+::1     localhost ip6-localhost ip6-loopback
+ff02::1 ip6-allnodes
+ff02::2 ip6-allrouters
diff --git a/package/base-files/files/etc/hotplug.d/leds/00-init b/package/base-files/files/etc/hotplug.d/leds/00-init
new file mode 100644
index 0000000..0303e2b
--- /dev/null
+++ b/package/base-files/files/etc/hotplug.d/leds/00-init
@@ -0,0 +1,3 @@
+#!/bin/sh
+
+[ "$ACTION" = "add" ] && /etc/init.d/led start "$DEVICENAME"
diff --git a/package/base-files/files/etc/hotplug.d/net/00-sysctl b/package/base-files/files/etc/hotplug.d/net/00-sysctl
new file mode 100644
index 0000000..8abe7f8
--- /dev/null
+++ b/package/base-files/files/etc/hotplug.d/net/00-sysctl
@@ -0,0 +1,9 @@
+#!/bin/sh
+
+if [ "$ACTION" = add ]; then
+	for CONF in /etc/sysctl.d/*.conf /etc/sysctl.conf; do
+		[ ! -f "$CONF" ] && continue;
+		sed -ne "/^[[:space:]]*net\..*\.$DEVICENAME\./p" "$CONF" | \
+			sysctl -e -p - | logger -t sysctl
+	done
+fi
diff --git a/package/base-files/files/etc/init.d/boot b/package/base-files/files/etc/init.d/boot
new file mode 100755
index 0000000..d91f591
--- /dev/null
+++ b/package/base-files/files/etc/init.d/boot
@@ -0,0 +1,62 @@
+#!/bin/sh /etc/rc.common
+# Copyright (C) 2006-2011 OpenWrt.org
+
+START=10
+STOP=90
+
+uci_apply_defaults() {
+	. /lib/functions/system.sh
+
+	cd /etc/uci-defaults || return 0
+	files="$(ls)"
+	[ -z "$files" ] && return 0
+	for file in $files; do
+		( . "./$(basename $file)" ) && rm -f "$file"
+	done
+	uci commit
+}
+
+boot() {
+	[ -f /proc/mounts ] || /sbin/mount_root
+	[ -f /proc/jffs2_bbc ] && echo "S" > /proc/jffs2_bbc
+	[ -f /proc/net/vlan/config ] && vconfig set_name_type DEV_PLUS_VID_NO_PAD
+
+	mkdir -p /var/lock
+	chmod 1777 /var/lock
+	mkdir -p /var/log
+	mkdir -p /var/run
+	ln -s /var/run /run
+	ln -s /var/lock /run/lock
+	mkdir -p /var/state
+	mkdir -p /var/tmp
+	mkdir -p /var/camera
+	mkdir -p /tmp/.uci
+	chmod 0700 /tmp/.uci
+	echo 0 > /tmp/dBm
+	touch /var/log/wtmp
+	touch /var/log/lastlog
+	mkdir -p /tmp/resolv.conf.d
+	touch /tmp/resolv.conf.d/resolv.conf.auto
+	ln -sf /tmp/resolv.conf.d/resolv.conf.auto /tmp/resolv.conf
+	grep -q debugfs /proc/filesystems && /bin/mount -o nosuid,nodev,noexec,noatime -t debugfs debugfs /sys/kernel/debug
+	grep -q bpf /proc/filesystems && /bin/mount -o nosuid,nodev,noexec,noatime,mode=0700 -t bpf bpffs /sys/fs/bpf
+	grep -q pstore /proc/filesystems && /bin/mount -o nosuid,nodev,noexec,noatime -t pstore pstore /sys/fs/pstore
+	[ "$FAILSAFE" = "true" ] && touch /tmp/.failsafe
+
+	touch /tmp/.config_pending
+	/bin/pppmodem &
+
+	mkdir -p /tmp/.uci
+	[ -f /etc/uci-defaults/30_uboot-envtools ] && (. /etc/uci-defaults/30_uboot-envtools)
+	/bin/config_generate
+	rm -f /tmp/.config_pending
+	/sbin/wifi config
+	uci_apply_defaults
+	sync
+	
+	# temporary hack until configd exists
+	/sbin/reload_config
+
+	# let mount done early to boot telephony success
+	[ -d /tmp/root ] && mount_root done
+}
diff --git a/package/base-files/files/etc/init.d/done b/package/base-files/files/etc/init.d/done
new file mode 100755
index 0000000..06b277c
--- /dev/null
+++ b/package/base-files/files/etc/init.d/done
@@ -0,0 +1,17 @@
+#!/bin/sh /etc/rc.common
+# Copyright (C) 2006 OpenWrt.org
+
+START=95
+boot() {
+	# mount_root done
+	rm -f /sysupgrade.tgz && sync
+
+	# process user commands
+	[ -f /etc/rc.local ] && {
+		sh /etc/rc.local
+	}
+
+	# set leds to normal state
+	. /etc/diag.sh
+	set_state done
+}
diff --git a/package/base-files/files/etc/init.d/gpio_switch b/package/base-files/files/etc/init.d/gpio_switch
new file mode 100755
index 0000000..24d790b
--- /dev/null
+++ b/package/base-files/files/etc/init.d/gpio_switch
@@ -0,0 +1,66 @@
+#!/bin/sh /etc/rc.common
+# Copyright (C) 2015 OpenWrt.org
+
+START=94
+STOP=10
+USE_PROCD=1
+
+
+load_gpio_switch()
+{
+	local name
+	local gpio_pin
+	local value
+
+	config_get gpio_pin "$1" gpio_pin
+	config_get name "$1" name
+	config_get value "$1" value 0
+
+	[ -z "$gpio_pin" ] && {
+		echo >&2 "Skipping gpio_switch '$name' due to missing gpio_pin"
+		return 1
+	}
+
+	local gpio_path
+	if [ -n "$(echo "$gpio_pin" | grep -E "^[0-9]+$")" ]; then
+		gpio_path="/sys/class/gpio/gpio${gpio_pin}"
+
+		# export GPIO pin for access
+		[ -d "$gpio_path" ] || {
+			echo "$gpio_pin" >/sys/class/gpio/export
+			# we need to wait a bit until the GPIO appears
+			[ -d "$gpio_path" ] || sleep 1
+		}
+
+		# direction attribute only exists if the kernel supports changing the
+		# direction of a GPIO
+		if [ -e "${gpio_path}/direction" ]; then
+			# set the pin to output with high or low pin value
+			{ [ "$value" = "0" ] && echo "low" || echo "high"; } \
+				>"$gpio_path/direction"
+		else
+			{ [ "$value" = "0" ] && echo "0" || echo "1"; } \
+				>"$gpio_path/value"
+		fi
+	else
+		gpio_path="/sys/class/gpio/${gpio_pin}"
+
+		[ -d "$gpio_path" ] && {
+			{ [ "$value" = "0" ] && echo "0" || echo "1"; } \
+				>"$gpio_path/value"
+		}
+	fi
+}
+
+service_triggers()
+{
+	procd_add_reload_trigger "system"
+}
+
+start_service()
+{
+	[ -e /sys/class/gpio/ ] && {
+		config_load system
+		config_foreach load_gpio_switch gpio_switch
+	}
+}
diff --git a/package/base-files/files/etc/init.d/led b/package/base-files/files/etc/init.d/led
new file mode 100755
index 0000000..7f05254
--- /dev/null
+++ b/package/base-files/files/etc/init.d/led
@@ -0,0 +1,198 @@
+#!/bin/sh /etc/rc.common
+# Copyright (C) 2008 OpenWrt.org
+
+START=96
+
+led_color_set() {
+	local cfg="$1"
+	local sysfs="$2"
+
+	local max_b
+	local colors
+	local color
+	local multi_intensity
+	local value
+	local write
+
+	[ -e /sys/class/leds/${sysfs}/multi_intensity ] || return
+	[ -e /sys/class/leds/${sysfs}/multi_index ] || return
+
+	max_b="$(cat /sys/class/leds/${sysfs}/max_brightness)"
+	colors="$(cat /sys/class/leds/${sysfs}/multi_index | tr " " "\n")"
+	multi_intensity=""
+	for color in $colors; do
+		config_get value $1 "color_${color}" "0"
+		[ "$value" -gt 0 ] && write=1
+		[ "$value" -gt "$max_b" ] && value="$max_b"
+		multi_intensity="${multi_intensity}${value} "
+	done
+
+	# Check if any color is configured
+	[ "$write" = 1 ] || return
+	# Remove last whitespace
+	multi_intensity="${multi_intensity:0:-1}"
+
+	echo "setting '${name}' led color to '${multi_intensity}'"
+	echo "${multi_intensity}" > /sys/class/leds/${sysfs}/multi_intensity
+}
+
+load_led() {
+	local name
+	local sysfs
+	local trigger
+	local dev
+	local ports
+	local mode
+	local default
+	local delayon
+	local delayoff
+	local interval
+
+	config_get sysfs $1 sysfs
+	config_get name $1 name "$sysfs"
+	config_get trigger $1 trigger "none"
+	config_get dev $1 dev
+	config_get ports $1 port
+	config_get mode $1 mode
+	config_get_bool default $1 default "0"
+	config_get delayon $1 delayon
+	config_get delayoff $1 delayoff
+	config_get interval $1 interval "50"
+	config_get port_state $1 port_state
+	config_get delay $1 delay "150"
+	config_get message $1 message ""
+	config_get gpio $1 gpio "0"
+	config_get_bool inverted $1 inverted "0"
+
+	[ "$2" ] && [ "$sysfs" != "$2" ] && return
+
+	# execute application led trigger
+	[ -f "/usr/libexec/led-trigger/${trigger}" ] && {
+		. "/usr/libexec/led-trigger/${trigger}"
+		return 0
+	}
+
+	[ "$trigger" = "usbdev" ] && {
+		# Backward compatibility: translate to the new trigger
+		trigger="usbport"
+		# Translate port of root hub, e.g. 4-1 -> usb4-port1
+		ports=$(echo "$dev" | sed -n 's/^\([0-9]*\)-\([0-9]*\)$/usb\1-port\2/p')
+		# Translate port of extra hub, e.g. 2-2.4 -> 2-2-port4
+		[ -z "$ports" ] && ports=$(echo "$dev" | sed -n 's/\./-port/p')
+	}
+
+	[ -e /sys/class/leds/${sysfs}/brightness ] && {
+		echo "setting up led ${name}"
+
+		printf "%s %s %d" \
+			"$sysfs" \
+			"$(sed -ne 's/^.*\[\(.*\)\].*$/\1/p' /sys/class/leds/${sysfs}/trigger)" \
+			"$(cat /sys/class/leds/${sysfs}/brightness)" \
+				>> /var/run/led.state
+		# Save default color if supported
+		[ -e /sys/class/leds/${sysfs}/multi_intensity ] && {
+			printf " %s" \
+				"$(sed 's/\ /:/g' /sys/class/leds/${sysfs}/multi_intensity)" \
+				>> /var/run/led.state
+		}
+		printf "\n" >> /var/run/led.state
+
+		[ "$default" = 0 ] &&
+			echo 0 >/sys/class/leds/${sysfs}/brightness
+
+		[ $default = 1 ] &&
+			cat /sys/class/leds/${sysfs}/max_brightness > /sys/class/leds/${sysfs}/brightness
+
+		led_color_set "$1" "$sysfs"
+
+		echo $trigger > /sys/class/leds/${sysfs}/trigger 2> /dev/null
+		ret="$?"
+		[ $ret = 0 ] || {
+			echo >&2 "Skipping trigger '$trigger' for led '$name' due to missing kernel module"
+			return 1
+		}
+		case "$trigger" in
+		"heartbeat")
+			echo "${inverted}" > "/sys/class/leds/${sysfs}/invert"
+			;;
+
+		"netdev")
+			[ -n "$dev" ] && {
+				echo $dev > /sys/class/leds/${sysfs}/device_name
+				for m in $mode; do
+					[ -e "/sys/class/leds/${sysfs}/$m" ] && \
+						echo 1 > /sys/class/leds/${sysfs}/$m
+				done
+				echo $interval > /sys/class/leds/${sysfs}/interval 2>/dev/null
+			}
+			;;
+
+		"timer"|"oneshot")
+			[ -n "$delayon" ] && \
+				echo $delayon > /sys/class/leds/${sysfs}/delay_on
+			[ -n "$delayoff" ] && \
+				echo $delayoff > /sys/class/leds/${sysfs}/delay_off
+			;;
+
+		"usbport")
+			local p
+
+			for p in $ports; do
+				echo 1 > /sys/class/leds/${sysfs}/ports/$p
+			done
+			;;
+
+		"port_state")
+			[ -n "$port_state" ] && \
+				echo $port_state > /sys/class/leds/${sysfs}/port_state
+			;;
+
+		"gpio")
+			echo $gpio > /sys/class/leds/${sysfs}/gpio
+			echo $inverted > /sys/class/leds/${sysfs}/inverted
+			;;
+
+		switch[0-9]*)
+			local port_mask speed_mask
+
+			config_get port_mask $1 port_mask
+			[ -n "$port_mask" ] && \
+				echo $port_mask > /sys/class/leds/${sysfs}/port_mask
+			config_get speed_mask $1 speed_mask
+			[ -n "$speed_mask" ] && \
+				echo $speed_mask > /sys/class/leds/${sysfs}/speed_mask
+			[ -n "$mode" ] && \
+				echo "$mode" > /sys/class/leds/${sysfs}/mode
+			;;
+		esac
+	}
+}
+
+start() {
+	[ -e /sys/class/leds/ ] && {
+		[ -s /var/run/led.state ] && {
+			local led trigger brightness color
+			while read led trigger brightness color; do
+				[ "$1" ] && [ "$1" != "$led" ] && continue
+				[ -e "/sys/class/leds/$led/trigger" ] && \
+					echo "$trigger" > "/sys/class/leds/$led/trigger"
+
+				[ -e "/sys/class/leds/$led/brightness" ] && \
+					echo "$brightness" > "/sys/class/leds/$led/brightness"
+
+				[ -e "/sys/class/leds/$led/multi_intensity" ] && \
+					echo "$color" | sed 's/:/\ /g' > \
+						"/sys/class/leds/$led/multi_intensity"
+			done < /var/run/led.state
+			if [ "$1" ]; then
+				grep -v "^$1 " /var/run/led.state > /var/run/led.state.new
+				mv /var/run/led.state.new /var/run/led.state
+			else
+				rm /var/run/led.state
+			fi
+		}
+
+		config_load system
+		config_foreach load_led led "$1"
+	}
+}
diff --git a/package/base-files/files/etc/init.d/sysctl b/package/base-files/files/etc/init.d/sysctl
new file mode 100755
index 0000000..88c822b
--- /dev/null
+++ b/package/base-files/files/etc/init.d/sysctl
@@ -0,0 +1,44 @@
+#!/bin/sh /etc/rc.common
+# Copyright (C) 2006 OpenWrt.org
+
+START=11
+
+apply_defaults() {
+	local mem="$(awk '/^MemTotal:/ {print $2}' /proc/meminfo)"
+	local min_free frag_low_thresh frag_high_thresh
+
+	if [ "$mem" -gt 131072 ]; then # >=256M DDR device
+		min_free=8192
+	elif [ "$mem" -gt 65536 ]; then # 128M DDR device
+		min_free=4196
+	else
+		min_free=1024
+		frag_low_thresh=393216
+		frag_high_thresh=524288
+	fi
+
+	sysctl -qw vm.min_free_kbytes="$min_free"
+
+	[ "$frag_low_thresh" ] && sysctl -qw \
+		net.ipv4.ipfrag_low_thresh="$frag_low_thresh" \
+		net.ipv4.ipfrag_high_thresh="$frag_high_thresh" \
+		net.ipv6.ip6frag_low_thresh="$frag_low_thresh" \
+		net.ipv6.ip6frag_high_thresh="$frag_high_thresh" \
+		net.netfilter.nf_conntrack_frag6_low_thresh="$frag_low_thresh" \
+		net.netfilter.nf_conntrack_frag6_high_thresh="$frag_high_thresh"
+
+	# first set default, then all interfaces to avoid races with appearing interfaces
+	if [ -d /proc/sys/net/ipv6/conf ]; then
+		echo 0 > /proc/sys/net/ipv6/conf/default/accept_ra
+		for iface in /proc/sys/net/ipv6/conf/*/accept_ra; do
+			echo 0 > "$iface"
+		done
+	fi
+}
+
+start() {
+	apply_defaults
+	for CONF in /etc/sysctl.d/*.conf /etc/sysctl.conf; do
+		[ -f "$CONF" ] && sysctl -e -p "$CONF" >&-
+	done
+}
diff --git a/package/base-files/files/etc/init.d/sysfixtime b/package/base-files/files/etc/init.d/sysfixtime
new file mode 100755
index 0000000..93f7922
--- /dev/null
+++ b/package/base-files/files/etc/init.d/sysfixtime
@@ -0,0 +1,44 @@
+#!/bin/sh /etc/rc.common
+# Copyright (C) 2013-2014 OpenWrt.org
+
+START=00
+STOP=90
+
+RTC_DEV=/dev/rtc0
+HWCLOCK=/sbin/hwclock
+
+boot() {
+	hwclock_load
+	local maxtime="$(find_max_time)"
+	local curtime="$(date +%s)"
+	if [ $curtime -lt $maxtime ]; then
+		date -s @$maxtime
+		hwclock_save
+	fi
+}
+
+start() {
+	hwclock_load
+}
+
+stop() {
+	hwclock_save
+}
+
+hwclock_load() {
+	[ -e "$RTC_DEV" ] && [ -e "$HWCLOCK" ] && $HWCLOCK -s -u -f $RTC_DEV
+}
+
+hwclock_save(){
+	[ -e "$RTC_DEV" ] && [ -e "$HWCLOCK" ] && $HWCLOCK -w -u -f $RTC_DEV && \
+		logger -t sysfixtime "saved '$(date)' to $RTC_DEV"
+}
+
+find_max_time() {
+	local file newest
+
+	for file in $( find /etc -type f ) ; do
+		[ -z "$newest" -o "$newest" -ot "$file" ] && newest=$file
+	done
+	[ "$newest" ] && date -r "$newest" +%s
+}
diff --git a/package/base-files/files/etc/init.d/system b/package/base-files/files/etc/init.d/system
new file mode 100755
index 0000000..042e018
--- /dev/null
+++ b/package/base-files/files/etc/init.d/system
@@ -0,0 +1,45 @@
+#!/bin/sh /etc/rc.common
+# Copyright (C) 2014 OpenWrt.org
+
+START=11
+USE_PROCD=1
+
+validate_system_section() {
+	uci_load_validate system system "$1" "$2" \
+		'hostname:string:OpenWrt' \
+		'conloglevel:uinteger' \
+		'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}
+	echo "$timezone" > /tmp/TZ
+	[ -n "$zonename" ] && [ -f "/usr/share/zoneinfo/${zonename// /_}" ] \
+		&& ln -sf "/usr/share/zoneinfo/${zonename// /_}" /tmp/localtime \
+		&& rm -f /tmp/TZ
+
+	# apply timezone to kernel
+	hwclock -u --systz
+}
+
+reload_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
+}
+
+start_service() {
+	reload_service
+}
diff --git a/package/base-files/files/etc/init.d/umount b/package/base-files/files/etc/init.d/umount
new file mode 100755
index 0000000..5dd9acc
--- /dev/null
+++ b/package/base-files/files/etc/init.d/umount
@@ -0,0 +1,22 @@
+#!/bin/sh /etc/rc.common
+# Copyright (C) 2006 OpenWrt.org
+
+STOP=90
+
+restart() {
+	:
+}
+
+revert_overlay() {
+	#kill all process to release mnt/
+	kill -9 -1
+
+	/bin/umount /overlay/etc
+	/bin/umount /overlay/nvm
+}
+
+stop() {
+	sync
+	revert_overlay
+	/bin/umount -a -d -r
+}
diff --git a/package/base-files/files/etc/inittab b/package/base-files/files/etc/inittab
new file mode 100644
index 0000000..9820e71
--- /dev/null
+++ b/package/base-files/files/etc/inittab
@@ -0,0 +1,3 @@
+::sysinit:/etc/init.d/rcS S boot
+::shutdown:/etc/init.d/rcS K shutdown
+::askconsole:/usr/libexec/login.sh
diff --git a/package/base-files/files/etc/iproute2/ematch_map b/package/base-files/files/etc/iproute2/ematch_map
new file mode 100644
index 0000000..4d6bb2f
--- /dev/null
+++ b/package/base-files/files/etc/iproute2/ematch_map
@@ -0,0 +1,8 @@
+# lookup table for ematch kinds
+1	cmp
+2	nbyte
+3	u32
+4	meta
+7	canid
+8	ipset
+9	ipt
diff --git a/package/base-files/files/etc/iproute2/rt_protos b/package/base-files/files/etc/iproute2/rt_protos
new file mode 100644
index 0000000..5b61798
--- /dev/null
+++ b/package/base-files/files/etc/iproute2/rt_protos
@@ -0,0 +1,18 @@
+#
+# Reserved protocols.
+#
+0	unspec
+1	redirect
+2	kernel
+3	boot
+4	static
+8	gated
+9	ra
+10	mrt
+11	zebra
+12	bird
+13	dnrouted
+14	xorp
+15	ntk
+16	dhcp
+42	babel
diff --git a/package/base-files/files/etc/iproute2/rt_tables b/package/base-files/files/etc/iproute2/rt_tables
new file mode 100644
index 0000000..5fc09b3
--- /dev/null
+++ b/package/base-files/files/etc/iproute2/rt_tables
@@ -0,0 +1,12 @@
+#
+# reserved values
+#
+128	prelocal
+255	local
+254	main
+253	default
+0	unspec
+#
+# local
+#
+#1	inr.ruhep
diff --git a/package/base-files/files/etc/openwrt_release b/package/base-files/files/etc/openwrt_release
new file mode 100644
index 0000000..d03400c
--- /dev/null
+++ b/package/base-files/files/etc/openwrt_release
@@ -0,0 +1,7 @@
+DISTRIB_ID='%D'
+DISTRIB_RELEASE='%V'
+DISTRIB_REVISION='%R'
+DISTRIB_TARGET='%S'
+DISTRIB_ARCH='%A'
+DISTRIB_DESCRIPTION='%D %V %C'
+DISTRIB_TAINTS='%t'
diff --git a/package/base-files/files/etc/openwrt_version b/package/base-files/files/etc/openwrt_version
new file mode 100644
index 0000000..48157ed
--- /dev/null
+++ b/package/base-files/files/etc/openwrt_version
@@ -0,0 +1 @@
+%C
diff --git a/package/base-files/files/etc/os-release b/package/base-files/files/etc/os-release
new file mode 120000
index 0000000..c4c75b4
--- /dev/null
+++ b/package/base-files/files/etc/os-release
@@ -0,0 +1 @@
+../usr/lib/os-release
\ No newline at end of file
diff --git a/package/base-files/files/etc/passwd b/package/base-files/files/etc/passwd
new file mode 100644
index 0000000..1d06a80
--- /dev/null
+++ b/package/base-files/files/etc/passwd
@@ -0,0 +1,5 @@
+root:x:0:0:root:/root:/bin/ash
+daemon:*:1:1:daemon:/var:/bin/false
+ftp:*:55:55:ftp:/home/ftp:/bin/false
+network:*:101:101:network:/var:/bin/false
+nobody:*:65534:65534:nobody:/var:/bin/false
diff --git a/package/base-files/files/etc/preinit b/package/base-files/files/etc/preinit
new file mode 100755
index 0000000..75c380f
--- /dev/null
+++ b/package/base-files/files/etc/preinit
@@ -0,0 +1,33 @@
+#!/bin/sh
+# Copyright (C) 2006-2016 OpenWrt.org
+# Copyright (C) 2010 Vertical Communications
+
+[ -z "$PREINIT" ] && exec /sbin/init
+
+export PATH="%PATH%"
+
+. /lib/functions.sh
+. /lib/functions/preinit.sh
+. /lib/functions/system.sh
+
+boot_hook_init preinit_essential
+boot_hook_init preinit_main
+boot_hook_init failsafe
+boot_hook_init initramfs
+boot_hook_init preinit_mount_root
+
+for pi_source_file in /lib/preinit/*; do
+	. $pi_source_file
+done
+
+or_failsafe_wait_timeout=$(awk 'BEGIN { RS=" "; FS="="; } $1 == "failsafe_wait" { print $2 }' < /proc/cmdline)
+[ -z "$or_failsafe_wait_timeout" ] || fs_failsafe_wait_timeout=$or_failsafe_wait_timeout
+[ "$fs_failsafe_wait_timeout" = "0" ] && pi_preinit_no_failsafe=y
+
+boot_run_hook preinit_essential
+
+pi_mount_skip_next=false
+pi_jffs2_mount_success=false
+pi_failsafe_net_message=false
+
+boot_run_hook preinit_main
diff --git a/package/base-files/files/etc/profile b/package/base-files/files/etc/profile
new file mode 100644
index 0000000..76b149b
--- /dev/null
+++ b/package/base-files/files/etc/profile
@@ -0,0 +1,40 @@
+[ -e /tmp/.failsafe ] && export FAILSAFE=1
+
+[ -f /etc/banner ] && cat /etc/banner
+[ -n "$FAILSAFE" ] && cat /etc/banner.failsafe
+
+grep -Fsq '/ overlay ro,' /proc/mounts && {
+	echo 'Your JFFS2-partition seems full and overlayfs is mounted read-only.'
+	echo 'Please try to remove files from /overlay/upper/... and reboot!'
+}
+
+export PATH="%PATH%"
+export HOME=$(grep -e "^${USER:-root}:" /etc/passwd | cut -d ":" -f 6)
+export HOME=${HOME:-/root}
+export PS1='\u@\h:\w\$ '
+export ENV=/etc/shinit
+
+case "$TERM" in
+	xterm*|rxvt*)
+		export PS1='\[\e]0;\u@\h: \w\a\]'$PS1
+		;;
+esac
+
+[ -n "$FAILSAFE" ] || {
+	for FILE in /etc/profile.d/*.sh; do
+		[ -e "$FILE" ] && . "$FILE"
+	done
+	unset FILE
+}
+
+if ( grep -qs '^root::' /etc/shadow && \
+     [ -z "$FAILSAFE" ] )
+then
+cat << EOF
+=== WARNING! =====================================
+There is no root password defined on this device!
+Use the "passwd" command to set up a new password
+in order to prevent unauthorized SSH logins.
+--------------------------------------------------
+EOF
+fi
diff --git a/package/base-files/files/etc/protocols b/package/base-files/files/etc/protocols
new file mode 100644
index 0000000..26bc775
--- /dev/null
+++ b/package/base-files/files/etc/protocols
@@ -0,0 +1,57 @@
+# Internet (IP) protocols
+#
+# Updated from http://www.iana.org/assignments/protocol-numbers and other
+# sources.
+# New protocols will be added on request if they have been officially
+# assigned by IANA and are not historical.
+# If you need a huge list of used numbers please install the nmap package.
+
+ip	0	IP		# internet protocol, pseudo protocol number
+#hopopt	0	HOPOPT		# IPv6 Hop-by-Hop Option [RFC1883]
+icmp	1	ICMP		# internet control message protocol
+igmp	2	IGMP		# Internet Group Management
+ggp	3	GGP		# gateway-gateway protocol
+ipencap	4	IP-ENCAP	# IP encapsulated in IP (officially ``IP'')
+st	5	ST		# ST datagram mode
+tcp	6	TCP		# transmission control protocol
+egp	8	EGP		# exterior gateway protocol
+igp	9	IGP		# any private interior gateway (Cisco)
+pup	12	PUP		# PARC universal packet protocol
+udp	17	UDP		# user datagram protocol
+hmp	20	HMP		# host monitoring protocol
+xns-idp	22	XNS-IDP		# Xerox NS IDP
+rdp	27	RDP		# "reliable datagram" protocol
+iso-tp4	29	ISO-TP4		# ISO Transport Protocol class 4 [RFC905]
+dccp	33	DCCP		# Datagram Congestion Control Protocol [RFC4340]
+xtp	36	XTP		# Xpress Transfer Protocol
+ddp	37	DDP		# Datagram Delivery Protocol
+idpr-cmtp 38	IDPR-CMTP	# IDPR Control Message Transport
+ipv6	41	IPv6		# Internet Protocol, version 6
+ipv6-route 43	IPv6-Route	# Routing Header for IPv6
+ipv6-frag 44	IPv6-Frag	# Fragment Header for IPv6
+idrp	45	IDRP		# Inter-Domain Routing Protocol
+rsvp	46	RSVP		# Reservation Protocol
+gre	47	GRE		# General Routing Encapsulation
+esp	50	IPSEC-ESP	# Encap Security Payload [RFC2046]
+ah	51	IPSEC-AH	# Authentication Header [RFC2402]
+skip	57	SKIP		# SKIP
+ipv6-icmp 58	IPv6-ICMP	# ICMP for IPv6
+ipv6-nonxt 59	IPv6-NoNxt	# No Next Header for IPv6
+ipv6-opts 60	IPv6-Opts	# Destination Options for IPv6
+rspf	73	RSPF CPHB	# Radio Shortest Path First (officially CPHB)
+vmtp	81	VMTP		# Versatile Message Transport
+eigrp	88	EIGRP		# Enhanced Interior Routing Protocol (Cisco)
+ospf	89	OSPFIGP		# Open Shortest Path First IGP
+ax.25	93	AX.25		# AX.25 frames
+ipip	94	IPIP		# IP-within-IP Encapsulation Protocol
+etherip	97	ETHERIP		# Ethernet-within-IP Encapsulation [RFC3378]
+encap	98	ENCAP		# Yet Another IP encapsulation [RFC1241]
+#	99			# any private encryption scheme
+pim	103	PIM		# Protocol Independent Multicast
+ipcomp	108	IPCOMP		# IP Payload Compression Protocol
+vrrp	112	VRRP		# Virtual Router Redundancy Protocol
+l2tp	115	L2TP		# Layer Two Tunneling Protocol [RFC2661]
+isis	124	ISIS		# IS-IS over IPv4
+sctp	132	SCTP		# Stream Control Transmission Protocol
+fc	133	FC		# Fibre Channel
+
diff --git a/package/base-files/files/etc/rc.button/failsafe b/package/base-files/files/etc/rc.button/failsafe
new file mode 100755
index 0000000..ba958fa
--- /dev/null
+++ b/package/base-files/files/etc/rc.button/failsafe
@@ -0,0 +1,5 @@
+#!/bin/sh
+
+[ "${TYPE}" = "switch" ] || echo ${BUTTON} > /tmp/failsafe_button
+
+return 0
diff --git a/package/base-files/files/etc/rc.button/power b/package/base-files/files/etc/rc.button/power
new file mode 100755
index 0000000..0080e0e
--- /dev/null
+++ b/package/base-files/files/etc/rc.button/power
@@ -0,0 +1,19 @@
+#!/bin/sh
+
+[ "${ACTION}" = "released" ] || exit 0
+
+. /lib/functions.sh
+
+logger "$BUTTON pressed for $SEEN seconds"
+
+if [ "$SEEN" -lt 3 ]
+then
+	echo "Please press 3s" > /dev/console
+#elif [ "$SEEN" -ge 3 -a "$SEEN" -lt 5]
+#then
+#	echo "3-5s" > /dev/console
+elif [ "$SEEN" -gt 3 ]
+then
+fi
+
+return 0
diff --git a/package/base-files/files/etc/rc.button/reboot b/package/base-files/files/etc/rc.button/reboot
new file mode 100755
index 0000000..cd547e3
--- /dev/null
+++ b/package/base-files/files/etc/rc.button/reboot
@@ -0,0 +1,12 @@
+#!/bin/sh
+
+[ "${ACTION}" = "released" ] || exit 0
+
+if [ "$SEEN" -ge 5 ]
+then
+	echo "REBOOT" > /dev/console
+	sync
+	reboot
+fi
+
+return 0
diff --git a/package/base-files/files/etc/rc.button/reset b/package/base-files/files/etc/rc.button/reset
new file mode 100755
index 0000000..2403122
--- /dev/null
+++ b/package/base-files/files/etc/rc.button/reset
@@ -0,0 +1,31 @@
+#!/bin/sh
+
+. /lib/functions.sh
+
+OVERLAY="$( grep ' /overlay ' /proc/mounts )"
+
+case "$ACTION" in
+pressed)
+	[ -z "$OVERLAY" ] && return 0
+
+	return 5
+;;
+timeout)
+	. /etc/diag.sh
+	set_state failsafe
+;;
+released)
+	if [ "$SEEN" -lt 1 ]
+	then
+		echo "REBOOT" > /dev/console
+		sync
+		reboot
+	elif [ "$SEEN" -ge 5 -a -n "$OVERLAY" ]
+	then
+		echo "FACTORY RESET" > /dev/console
+		jffs2reset -y && reboot &
+	fi
+;;
+esac
+
+return 0
diff --git a/package/base-files/files/etc/rc.button/rfkill b/package/base-files/files/etc/rc.button/rfkill
new file mode 100755
index 0000000..fbdda40
--- /dev/null
+++ b/package/base-files/files/etc/rc.button/rfkill
@@ -0,0 +1,32 @@
+#!/bin/sh
+
+[ "${ACTION}" = "released" -o -n "${TYPE}" ] || exit 0
+
+. /lib/functions.sh
+
+rfkill_state=0
+
+wifi_rfkill_set() {
+	uci set wireless.$1.disabled=$rfkill_state
+}
+
+wifi_rfkill_check() {
+	local disabled
+	config_get disabled $1 disabled
+	[ "$disabled" = "1" ] || rfkill_state=1
+}
+
+config_load wireless
+case "${TYPE}" in
+"switch")
+	[ "${ACTION}" = "released" ] && rfkill_state=1
+	;;
+*)
+	config_foreach wifi_rfkill_check wifi-device
+	;;
+esac
+config_foreach wifi_rfkill_set wifi-device
+uci commit wireless
+wifi up
+
+return 0
diff --git a/package/base-files/files/etc/rc.common b/package/base-files/files/etc/rc.common
new file mode 100755
index 0000000..abf72ea
--- /dev/null
+++ b/package/base-files/files/etc/rc.common
@@ -0,0 +1,190 @@
+#!/bin/sh
+# Copyright (C) 2006-2012 OpenWrt.org
+
+. $IPKG_INSTROOT/lib/functions.sh
+. $IPKG_INSTROOT/lib/functions/service.sh
+
+initscript=$1
+action=${2:-help}
+shift 2
+
+start() {
+	return 0
+}
+
+stop() {
+	return 0
+}
+
+reload() {
+	restart
+}
+
+restart() {
+	trap '' TERM
+	stop "$@"
+	trap - TERM
+	start "$@"
+}
+
+boot() {
+	start "$@"
+}
+
+shutdown() {
+	stop
+}
+
+disable() {
+	name="$(basename "${initscript}")"
+	rm -f "$IPKG_INSTROOT"/etc/rc.d/S??$name
+	rm -f "$IPKG_INSTROOT"/etc/rc.d/K??$name
+}
+
+enable() {
+	err=1
+	name="$(basename "${initscript}")"
+	[ "$START" ] && \
+		ln -sf "../init.d/$name" "$IPKG_INSTROOT/etc/rc.d/S${START}${name##S[0-9][0-9]}" && \
+		err=0
+	[ "$STOP" ] && \
+		ln -sf "../init.d/$name" "$IPKG_INSTROOT/etc/rc.d/K${STOP}${name##K[0-9][0-9]}" && \
+		err=0
+	return $err
+}
+
+enabled() {
+	name="$(basename "${initscript}")"
+	name="${name##[SK][0-9][0-9]}"
+	{
+		[ -z "${START:-}" ] || [ -L "$IPKG_INSTROOT/etc/rc.d/S${START}$name" ]
+	} && {
+		[ -z "${STOP:-}" ] || [ -L "$IPKG_INSTROOT/etc/rc.d/K${STOP}$name" ]
+	}
+}
+
+depends() {
+	return 0
+}
+
+ALL_HELP=""
+ALL_COMMANDS="boot shutdown depends"
+extra_command() {
+	local cmd="$1"
+	local help="$2"
+
+	local extra="$(printf "%-16s%s" "${cmd}" "${help}")"
+	ALL_HELP="${ALL_HELP}\t${extra}\n"
+	ALL_COMMANDS="${ALL_COMMANDS} ${cmd}"
+}
+
+help() {
+	cat <<EOF
+Syntax: $initscript [command]
+
+Available commands:
+EOF
+	echo -e "$ALL_HELP"
+}
+
+# for procd
+start_service() {
+	return 0
+}
+
+stop_service() {
+	return 0
+}
+
+service_triggers() {
+	return 0
+}
+
+service_running() {
+	local instance="${1:-*}"
+
+	procd_running "$(basename $initscript)" "$instance"
+}
+
+${INIT_TRACE:+set -x}
+
+extra_command "start" "Start the service"
+extra_command "stop" "Stop the service"
+extra_command "restart" "Restart the service"
+extra_command "reload" "Reload configuration files (or restart if service does not implement reload)"
+extra_command "enable" "Enable service autostart"
+extra_command "disable" "Disable service autostart"
+extra_command "enabled" "Check if service is started on boot"
+
+. "$initscript"
+
+[ -n "$USE_PROCD" ] && {
+	extra_command "running" "Check if service is running"
+	extra_command "status" "Service status"
+	extra_command "trace" "Start with syscall trace"
+	extra_command "info" "Dump procd service info"
+
+	. $IPKG_INSTROOT/lib/functions/procd.sh
+	basescript=$(readlink "$initscript")
+	rc_procd() {
+		local method="set"
+		[ -n "$2" ] && method="add"
+		procd_open_service "$(basename ${basescript:-$initscript})" "$initscript"
+		"$@"
+		procd_close_service "$method"
+	}
+
+	start() {
+		rc_procd start_service "$@"
+		if eval "type service_started" 2>/dev/null >/dev/null; then
+			service_started
+		fi
+	}
+
+	trace() {
+		TRACE_SYSCALLS=1
+		start "$@"
+	}
+
+	info() {
+		json_init
+		json_add_string name "$(basename ${basescript:-$initscript})"
+		json_add_boolean verbose "1"
+		_procd_ubus_call list
+	}
+
+	stop() {
+		procd_lock
+		stop_service "$@"
+		procd_kill "$(basename ${basescript:-$initscript})" "$1"
+		if eval "type service_stopped" 2>/dev/null >/dev/null; then
+			service_stopped
+		fi
+	}
+
+	reload() {
+		if eval "type reload_service" 2>/dev/null >/dev/null; then
+			procd_lock
+			reload_service "$@"
+		else
+			start
+		fi
+	}
+
+	running() {
+		service_running "$@"
+	}
+
+	status() {
+		if eval "type status_service" 2>/dev/null >/dev/null; then
+			status_service "$@"
+		else
+			_procd_status "$(basename ${basescript:-$initscript})" "$1"
+		fi
+	}
+}
+
+ALL_COMMANDS="${ALL_COMMANDS} ${EXTRA_COMMANDS}"
+ALL_HELP="${ALL_HELP}${EXTRA_HELP}"
+list_contains ALL_COMMANDS "$action" || action=help
+$action "$@"
diff --git a/package/base-files/files/etc/rc.local b/package/base-files/files/etc/rc.local
new file mode 100644
index 0000000..5639477
--- /dev/null
+++ b/package/base-files/files/etc/rc.local
@@ -0,0 +1,4 @@
+# Put your custom commands here that should be executed once
+# the system init finished. By default this file does nothing.
+
+exit 0
diff --git a/package/base-files/files/etc/services b/package/base-files/files/etc/services
new file mode 100644
index 0000000..968f9e7
--- /dev/null
+++ b/package/base-files/files/etc/services
@@ -0,0 +1,173 @@
+echo		7/tcp
+echo		7/udp
+discard		9/tcp
+discard		9/udp
+daytime		13/tcp
+daytime		13/udp
+netstat		15/tcp
+chargen		19/tcp
+chargen		19/udp
+ftp-data	20/tcp
+ftp		21/tcp
+ssh		22/tcp
+ssh		22/udp
+telnet		23/tcp
+smtp		25/tcp
+time		37/tcp
+time		37/udp
+whois		43/tcp
+domain		53/tcp
+domain		53/udp
+bootps		67/tcp
+bootps		67/udp
+bootpc		68/tcp
+bootpc		68/udp
+tftp		69/udp
+finger		79/tcp
+www		80/tcp		http
+kerberos	88/tcp		kerberos5 krb5 kerberos-sec
+kerberos	88/udp		kerberos5 krb5 kerberos-sec
+pop3		110/tcp
+pop3		110/udp
+sunrpc		111/tcp		rpcbind
+sunrpc		111/udp		rpcbind
+auth		113/tcp		ident
+sftp		115/tcp
+nntp		119/tcp
+ntp		123/tcp
+ntp		123/udp
+netbios-ns	137/tcp
+netbios-ns	137/udp
+netbios-dgm	138/tcp
+netbios-dgm	138/udp
+netbios-ssn	139/tcp
+netbios-ssn	139/udp
+imap2		143/tcp		imap
+imap2		143/udp		imap
+snmp		161/tcp
+snmp		161/udp
+snmp-trap	162/tcp		snmptrap
+snmp-trap	162/udp		snmptrap
+xdmcp		177/tcp
+xdmcp		177/udp
+bgp		179/tcp
+bgp		179/udp
+imap3		220/tcp
+imap3		220/udp
+ldap		389/tcp
+ldap		389/udp
+https		443/tcp
+https		443/udp
+microsoft-ds	445/tcp
+microsoft-ds	445/udp
+isakmp		500/tcp
+isakmp		500/udp
+rtsp		554/tcp
+rtsp		554/udp
+ipp		631/tcp
+ipp		631/udp
+syslog		514/udp
+printer		515/tcp		spooler
+dhcpv6-client	546/tcp
+dhcpv6-client	546/udp
+dhcpv6-server	547/tcp
+dhcpv6-server	547/udp
+afpovertcp	548/tcp
+afpovertcp	548/udp
+nntps		563/tcp		snntp
+nntps		563/udp		snntp
+submission	587/tcp
+submission	587/udp
+ldaps		636/tcp
+ldaps		636/udp
+tinc		655/tcp
+tinc		655/udp
+rsync		873/tcp
+rsync		873/udp
+ftps-data	989/tcp
+ftps		990/tcp
+imaps		993/tcp
+imaps		993/udp
+ircs		994/tcp
+ircs		994/udp
+pop3s		995/tcp
+pop3s		995/udp
+socks		1080/tcp
+socks		1080/udp
+openvpn		1194/tcp
+openvpn		1194/udp
+l2f		1701/tcp	l2tp
+l2f		1701/udp	l2tp
+radius		1812/tcp
+radius		1812/udp
+radius-acct	1813/tcp	radacct
+radius-acct	1813/udp	radacct
+nfs		2049/tcp
+nfs		2049/udp
+dict		2628/tcp
+dict		2628/udp
+gpsd		2947/tcp
+gpsd		2947/udp
+icpv2		3130/tcp	icp
+icpv2		3130/udp	icp
+mysql		3306/tcp
+mysql		3306/udp
+nut		3493/tcp
+nut		3493/udp
+distcc		3632/tcp
+distcc		3632/udp
+daap		3689/tcp
+daap		3689/udp
+svn		3690/tcp	subversion
+svn		3690/udp	subversion
+epmd		4369/tcp
+epmd		4369/udp
+iax		4569/tcp
+iax		4569/udp
+mtn		4691/tcp
+mtn		4691/udp
+munin		4949/tcp
+sip		5060/tcp
+sip		5060/udp
+sip-tls		5061/tcp
+sip-tls		5061/udp
+xmpp-client	5222/tcp	jabber-client
+xmpp-client	5222/udp	jabber-client
+xmpp-server	5269/tcp	jabber-server
+xmpp-server	5269/udp	jabber-server
+mdns		5353/tcp
+mdns		5353/udp
+postgresql	5432/tcp	postgres
+postgresql	5432/udp	postgres
+x11		6000/tcp
+x11		6000/udp
+mysql-proxy	6446/tcp
+mysql-proxy	6446/udp
+bacula-dir	9101/tcp
+bacula-dir	9101/udp
+bacula-fd	9102/tcp
+bacula-fd	9102/udp
+bacula-sd	9103/tcp
+bacula-sd	9103/udp
+nbd		10809/tcp
+zabbix-agent	10050/tcp
+zabbix-agent	10050/udp
+zabbix-trapper	10051/tcp
+zabbix-trapper	10051/udp
+hkp		11371/tcp
+hkp		11371/udp
+ssmtp		465/tcp		smtps
+spamd		783/tcp
+zebrasrv	2600/tcp
+zebra		2601/tcp
+ripd		2602/tcp
+ripngd		2603/tcp
+ospfd		2604/tcp
+bgpd		2605/tcp
+ospf6d		2606/tcp
+ospfapi		2607/tcp
+isisd		2608/tcp
+sane-port	6566/tcp	sane saned
+ircd		6667/tcp
+git		9418/tcp
+
diff --git a/package/base-files/files/etc/shadow b/package/base-files/files/etc/shadow
new file mode 100644
index 0000000..39bdb9c
--- /dev/null
+++ b/package/base-files/files/etc/shadow
@@ -0,0 +1,5 @@
+root:::0:99999:7:::
+daemon:*:0:0:99999:7:::
+ftp:*:0:0:99999:7:::
+network:*:0:0:99999:7:::
+nobody:*:0:0:99999:7:::
diff --git a/package/base-files/files/etc/shells b/package/base-files/files/etc/shells
new file mode 100644
index 0000000..006aa38
--- /dev/null
+++ b/package/base-files/files/etc/shells
@@ -0,0 +1 @@
+/bin/ash
diff --git a/package/base-files/files/etc/shinit b/package/base-files/files/etc/shinit
new file mode 100644
index 0000000..8df9771
--- /dev/null
+++ b/package/base-files/files/etc/shinit
@@ -0,0 +1,12 @@
+[ -x /bin/more ] || [ -x /usr/bin/more ] || alias more=less
+[ -x /usr/bin/vim ] && alias vi=vim || alias vim=vi
+
+alias ll='ls -alF --color=auto'
+
+[ -z "$KSH_VERSION" -o \! -s /etc/mkshrc ] || . /etc/mkshrc
+
+[ -x /usr/bin/arp -o -x /sbin/arp ] || arp() { cat /proc/net/arp; }
+[ -x /usr/bin/ldd ] || ldd() { LD_TRACE_LOADED_OBJECTS=1 $*; }
+
+[ -n "$KSH_VERSION" -o \! -s "$HOME/.shinit" ] || . "$HOME/.shinit"
+[ -z "$KSH_VERSION" -o \! -s "$HOME/.mkshrc" ] || . "$HOME/.mkshrc"
diff --git a/package/base-files/files/etc/sysctl.conf b/package/base-files/files/etc/sysctl.conf
new file mode 100644
index 0000000..10e10b3
--- /dev/null
+++ b/package/base-files/files/etc/sysctl.conf
@@ -0,0 +1,18 @@
+# Defaults are configured in /etc/sysctl.d/* and can be customized in this file
+
+net.ipv6.conf.ccinet0.accept_ra = 2
+net.ipv6.conf.ccinet1.accept_ra = 2
+net.ipv6.conf.ccinet2.accept_ra = 2
+net.ipv6.conf.ccinet3.accept_ra = 2
+net.ipv6.conf.ccinet4.accept_ra = 2
+net.ipv6.conf.ccinet5.accept_ra = 2
+net.ipv6.conf.ccinet6.accept_ra = 2
+net.ipv6.conf.ccinet7.accept_ra = 2
+net.ipv6.conf.ccinet8.accept_ra = 2
+net.ipv6.conf.ccinet9.accept_ra = 2
+net.ipv6.conf.ccinet10.accept_ra = 2
+net.ipv6.conf.ccinet11.accept_ra = 2
+net.ipv6.conf.ccinet12.accept_ra = 2
+net.ipv6.conf.ccinet13.accept_ra = 2
+net.ipv6.conf.ccinet14.accept_ra = 2
+net.ipv6.conf.ccinet15.accept_ra = 2
diff --git a/package/base-files/files/etc/sysctl.d/10-default.conf b/package/base-files/files/etc/sysctl.d/10-default.conf
new file mode 100644
index 0000000..ee7df2b
--- /dev/null
+++ b/package/base-files/files/etc/sysctl.d/10-default.conf
@@ -0,0 +1,28 @@
+# Do not edit, changes to this file will be lost on upgrades
+# /etc/sysctl.conf can be used to customize sysctl settings
+
+kernel.panic=3
+kernel.core_pattern=/tmp/%e.%t.%p.%s.core
+fs.suid_dumpable=2
+
+fs.protected_hardlinks=1
+fs.protected_symlinks=1
+
+net.core.bpf_jit_enable=1
+net.core.bpf_jit_kallsyms=1
+
+net.ipv4.conf.default.arp_ignore=1
+net.ipv4.conf.all.arp_ignore=1
+net.ipv4.ip_forward=1
+net.ipv4.icmp_echo_ignore_broadcasts=1
+net.ipv4.icmp_ignore_bogus_error_responses=1
+net.ipv4.igmp_max_memberships=100
+net.ipv4.tcp_fin_timeout=30
+net.ipv4.tcp_keepalive_time=120
+net.ipv4.tcp_syncookies=1
+net.ipv4.tcp_timestamps=1
+net.ipv4.tcp_sack=1
+net.ipv4.tcp_dsack=1
+
+net.ipv6.conf.default.forwarding=1
+net.ipv6.conf.all.forwarding=1
diff --git a/package/base-files/files/etc/sysupgrade.conf b/package/base-files/files/etc/sysupgrade.conf
new file mode 100644
index 0000000..e06fd5e
--- /dev/null
+++ b/package/base-files/files/etc/sysupgrade.conf
@@ -0,0 +1,5 @@
+## This file contains files and directories that should
+## be preserved during an upgrade.
+
+# /etc/example.conf
+# /etc/openvpn/
diff --git a/package/base-files/files/etc/uci-defaults/10_migrate-shadow b/package/base-files/files/etc/uci-defaults/10_migrate-shadow
new file mode 100644
index 0000000..481444f
--- /dev/null
+++ b/package/base-files/files/etc/uci-defaults/10_migrate-shadow
@@ -0,0 +1,10 @@
+ppwd="$(sed -ne '/^root:/s/^root:\([^:]*\):.*$/\1/p' /etc/passwd)"
+spwd="$(sed -ne '/^root:/s/^root:\([^:]*\):.*$/\1/p' /etc/shadow)"
+
+if [ -n "${ppwd#[\!x]}" ] && [ -z "${spwd#[\!x]}" ]; then
+	logger -t migrate-shadow "Moving root password hash into shadow database"
+	sed -i -e "s:^root\:[^\:]*\::root\:x\::"     /etc/passwd
+	sed -i -e "s:^root\:[^\:]*\::root\:$ppwd\::" /etc/shadow
+fi
+
+exit 0
diff --git a/package/base-files/files/etc/uci-defaults/11_network-migrate-bridges b/package/base-files/files/etc/uci-defaults/11_network-migrate-bridges
new file mode 100644
index 0000000..a9dece4
--- /dev/null
+++ b/package/base-files/files/etc/uci-defaults/11_network-migrate-bridges
@@ -0,0 +1,49 @@
+. /lib/functions.sh
+
+migrate_ports() {
+	local config="$1"
+	local type ports ifname
+
+	config_get type "$config" type
+	[ "$type" != "bridge" ] && return
+
+	config_get ports "$config" ports
+	[ -n "$ports" ] && return
+
+	config_get ifname "$config" ifname
+	[ -z "$ifname" ] && return
+
+	for port in $ifname; do
+		uci add_list network.$config.ports="$port"
+	done
+	uci delete network.$config.ifname
+}
+
+migrate_bridge() {
+	local config="$1"
+	local type ifname
+
+	config_get type "$config" type
+	[ "$type" != "bridge" ] && return
+
+	config_get ifname "$config" ifname
+
+	uci -q batch <<-EOF
+		add network device
+		set network.@device[-1].name='br-$config'
+		set network.@device[-1].type='bridge'
+	EOF
+	for port in $ifname; do
+		uci add_list network.@device[-1].ports="$port"
+	done
+
+	uci -q batch <<-EOF
+		delete network.$config.type
+		delete network.$config.ifname
+		set network.$config.device='br-$config'
+	EOF
+}
+
+config_load network
+config_foreach migrate_ports device
+config_foreach migrate_bridge interface
diff --git a/package/base-files/files/etc/uci-defaults/12_network-generate-ula b/package/base-files/files/etc/uci-defaults/12_network-generate-ula
new file mode 100644
index 0000000..060d0ef
--- /dev/null
+++ b/package/base-files/files/etc/uci-defaults/12_network-generate-ula
@@ -0,0 +1,9 @@
+[ "$(uci -q get network.globals.ula_prefix)" != "auto" ] && exit 0
+
+uci -q batch <<-EOF >/dev/null
+	set network.globals.ula_prefix="$(hexdump -vn 5 -e '"fd" 1/1 "%02x:" 2/2 "%x:"' /dev/urandom):/48"
+	commit network
+EOF
+
+exit 0
+
diff --git a/package/base-files/files/etc/uci-defaults/13_fix-group-user b/package/base-files/files/etc/uci-defaults/13_fix-group-user
new file mode 100644
index 0000000..c5cc74e
--- /dev/null
+++ b/package/base-files/files/etc/uci-defaults/13_fix-group-user
@@ -0,0 +1,12 @@
+. /lib/functions.sh
+
+# Skip if we don't have /usr/lib/opkg/info (APK installation)
+[ -d /usr/lib/opkg/info ] || exit 0
+
+for file in $(grep -sl Require-User /usr/lib/opkg/info/*.control); do
+	file="${file##*/}"
+	file="${file%.control}"
+	add_group_and_user "${file}"
+done
+
+exit 0
diff --git a/package/base-files/files/etc/uci-defaults/50-root-passwd b/package/base-files/files/etc/uci-defaults/50-root-passwd
new file mode 100644
index 0000000..f0bb519
--- /dev/null
+++ b/package/base-files/files/etc/uci-defaults/50-root-passwd
@@ -0,0 +1,18 @@
+. /usr/share/libubox/jshn.sh
+
+json_init
+json_load "$(cat /etc/board.json)"
+
+if json_is_a credentials object; then
+	json_select credentials
+		json_get_vars root_password_hash root_password_hash
+		if [ -n "$root_password_hash" ]; then
+			sed -i "s|^root:[^:]*|root:$root_password_hash|g" /etc/shadow
+		fi
+
+		json_get_vars root_password_plain root_password_plain
+		if [ -n "$root_password_plain" ]; then
+			(echo "$root_password_plain"; sleep 1; echo "$root_password_plain") | passwd root
+		fi
+	json_select ..
+fi
diff --git a/package/base-files/files/lib/functions.sh b/package/base-files/files/lib/functions.sh
new file mode 100644
index 0000000..658eafe
--- /dev/null
+++ b/package/base-files/files/lib/functions.sh
@@ -0,0 +1,562 @@
+# Copyright (C) 2006-2014 OpenWrt.org
+# Copyright (C) 2006 Fokus Fraunhofer <carsten.tittel@fokus.fraunhofer.de>
+# Copyright (C) 2010 Vertical Communications
+
+
+debug () {
+	${DEBUG:-:} "$@"
+}
+
+# newline
+N="
+"
+
+_C=0
+NO_EXPORT=1
+LOAD_STATE=1
+LIST_SEP=" "
+
+# xor multiple hex values of the same length
+xor() {
+	local val
+	local ret="0x$1"
+	local retlen=${#1}
+
+	shift
+	while [ -n "$1" ]; do
+		val="0x$1"
+		ret=$((ret ^ val))
+		shift
+	done
+
+	printf "%0${retlen}x" "$ret"
+}
+
+data_2bin() {
+	local data=$1
+	local len=${#1}
+	local bin_data
+
+	for i in $(seq 0 2 $(($len - 1))); do
+		bin_data="${bin_data}\x${data:i:2}"
+	done
+
+	echo -ne $bin_data
+}
+
+data_2xor_val() {
+	local data=$1
+	local len=${#1}
+	local xor_data
+
+	for i in $(seq 0 4 $(($len - 1))); do
+		xor_data="${xor_data}${data:i:4} "
+	done
+
+	echo -n ${xor_data:0:-1}
+}
+
+append() {
+	local var="$1"
+	local value="$2"
+	local sep="${3:- }"
+
+	eval "export ${NO_EXPORT:+-n} -- \"$var=\${$var:+\${$var}\${value:+\$sep}}\$value\""
+}
+
+prepend() {
+	local var="$1"
+	local value="$2"
+	local sep="${3:- }"
+
+	eval "export ${NO_EXPORT:+-n} -- \"$var=\$value\${$var:+\${sep}\${$var}}\""
+}
+
+list_contains() {
+	local var="$1"
+	local str="$2"
+	local val
+
+	eval "val=\" \${$var} \""
+	[ "${val%% $str *}" != "$val" ]
+}
+
+config_load() {
+	[ -n "$IPKG_INSTROOT" ] && return 0
+	uci_load "$@"
+}
+
+reset_cb() {
+	config_cb() { return 0; }
+	option_cb() { return 0; }
+	list_cb() { return 0; }
+}
+reset_cb
+
+package() {
+	return 0
+}
+
+config () {
+	local cfgtype="$1"
+	local name="$2"
+
+	export ${NO_EXPORT:+-n} CONFIG_NUM_SECTIONS=$((CONFIG_NUM_SECTIONS + 1))
+	name="${name:-cfg$CONFIG_NUM_SECTIONS}"
+	append CONFIG_SECTIONS "$name"
+	export ${NO_EXPORT:+-n} CONFIG_SECTION="$name"
+	config_set "$CONFIG_SECTION" "TYPE" "${cfgtype}"
+	[ -n "$NO_CALLBACK" ] || config_cb "$cfgtype" "$name"
+}
+
+option () {
+	local varname="$1"; shift
+	local value="$*"
+
+	config_set "$CONFIG_SECTION" "${varname}" "${value}"
+	[ -n "$NO_CALLBACK" ] || option_cb "$varname" "$*"
+}
+
+list() {
+	local varname="$1"; shift
+	local value="$*"
+	local len
+
+	config_get len "$CONFIG_SECTION" "${varname}_LENGTH" 0
+	[ $len = 0 ] && append CONFIG_LIST_STATE "${CONFIG_SECTION}_${varname}"
+	len=$((len + 1))
+	config_set "$CONFIG_SECTION" "${varname}_ITEM$len" "$value"
+	config_set "$CONFIG_SECTION" "${varname}_LENGTH" "$len"
+	append "CONFIG_${CONFIG_SECTION}_${varname}" "$value" "$LIST_SEP"
+	[ -n "$NO_CALLBACK" ] || list_cb "$varname" "$*"
+}
+
+config_unset() {
+	config_set "$1" "$2" ""
+}
+
+# config_get <variable> <section> <option> [<default>]
+# config_get <section> <option>
+config_get() {
+	case "$2${3:-$1}" in
+		*[!A-Za-z0-9_]*) : ;;
+		*)
+			case "$3" in
+				"") eval echo "\"\${CONFIG_${1}_${2}:-\${4}}\"";;
+				*)  eval export ${NO_EXPORT:+-n} -- "${1}=\${CONFIG_${2}_${3}:-\${4}}";;
+			esac
+		;;
+	esac
+}
+
+# get_bool <value> [<default>]
+get_bool() {
+	local _tmp="$1"
+	case "$_tmp" in
+		1|on|true|yes|enabled) _tmp=1;;
+		0|off|false|no|disabled) _tmp=0;;
+		*) _tmp="$2";;
+	esac
+	echo -n "$_tmp"
+}
+
+# config_get_bool <variable> <section> <option> [<default>]
+config_get_bool() {
+	local _tmp
+	config_get _tmp "$2" "$3" "$4"
+	_tmp="$(get_bool "$_tmp" "$4")"
+	export ${NO_EXPORT:+-n} "$1=$_tmp"
+}
+
+config_set() {
+	local section="$1"
+	local option="$2"
+	local value="$3"
+
+	export ${NO_EXPORT:+-n} "CONFIG_${section}_${option}=${value}"
+}
+
+config_add_list() {
+	local section="$1"
+	local option="$2"
+	local value="$3"
+	local old_section="$CONFIG_SECTION"
+
+	CONFIG_SECTION="$section"
+	list "$option" "$value"
+	CONFIG_SECTION="$old_section"
+}
+
+config_foreach() {
+	local ___function="$1"
+	[ "$#" -ge 1 ] && shift
+	local ___type="$1"
+	[ "$#" -ge 1 ] && shift
+	local section cfgtype
+
+	[ -z "$CONFIG_SECTIONS" ] && return 0
+	for section in ${CONFIG_SECTIONS}; do
+		config_get cfgtype "$section" TYPE
+		[ -n "$___type" ] && [ "x$cfgtype" != "x$___type" ] && continue
+		eval "$___function \"\$section\" \"\$@\""
+	done
+}
+
+config_list_foreach() {
+	[ "$#" -ge 3 ] || return 0
+	local section="$1"; shift
+	local option="$1"; shift
+	local function="$1"; shift
+	local val
+	local len
+	local c=1
+
+	config_get len "${section}" "${option}_LENGTH"
+	[ -z "$len" ] && return 0
+	while [ $c -le "$len" ]; do
+		config_get val "${section}" "${option}_ITEM$c"
+		eval "$function \"\$val\" \"\$@\""
+		c="$((c + 1))"
+	done
+}
+
+default_prerm() {
+	local root="${IPKG_INSTROOT}"
+	[ -z "$pkgname" ] && local pkgname="$(basename ${1%.*})"
+	local ret=0
+	local filelist="${root}/usr/lib/opkg/info/${pkgname}.list"
+	[ -f "$root/lib/apk/packages/${pkgname}.list" ] && filelist="$root/lib/apk/packages/${pkgname}.list"
+
+	if [ -f "$root/usr/lib/opkg/info/${pkgname}.prerm-pkg" ]; then
+		( . "$root/usr/lib/opkg/info/${pkgname}.prerm-pkg" )
+		ret=$?
+	fi
+
+	local shell="$(command -v bash)"
+	for i in $(grep -s "^/etc/init.d/" "$filelist"); do
+		if [ -n "$root" ]; then
+			${shell:-/bin/sh} "$root/etc/rc.common" "$root$i" disable
+		else
+			if [ "$PKG_UPGRADE" != "1" ]; then
+				"$i" disable
+			fi
+			"$i" stop
+		fi
+	done
+
+	return $ret
+}
+
+add_group_and_user() {
+	[ -z "$pkgname" ] && local pkgname="$(basename ${1%.*})"
+	local rusers="$(sed -ne 's/^Require-User: *//p' $root/usr/lib/opkg/info/${pkgname}.control 2>/dev/null)"
+	if [ -f "$root/lib/apk/packages/${pkgname}.rusers" ]; then
+		local rusers="$(cat $root/lib/apk/packages/${pkgname}.rusers)"
+	fi
+
+	if [ -n "$rusers" ]; then
+		local tuple oIFS="$IFS"
+		for tuple in $rusers; do
+			local uid gid uname gname addngroups addngroup addngname addngid
+
+			IFS=":"
+			set -- $tuple; uname="$1"; gname="$2"; addngroups="$3"
+			IFS="="
+			set -- $uname; uname="$1"; uid="$2"
+			set -- $gname; gname="$1"; gid="$2"
+			IFS="$oIFS"
+
+			if [ -n "$gname" ] && [ -n "$gid" ]; then
+				group_exists "$gname" || group_add "$gname" "$gid"
+			elif [ -n "$gname" ]; then
+				gid="$(group_add_next "$gname")"
+			fi
+
+			if [ -n "$uname" ]; then
+				user_exists "$uname" || user_add "$uname" "$uid" "$gid"
+			fi
+
+			if [ -n "$uname" ] && [ -n "$gname" ]; then
+				group_add_user "$gname" "$uname"
+			fi
+
+			if [ -n "$uname" ] &&  [ -n "$addngroups" ]; then
+				oIFS="$IFS"
+				IFS=","
+				for addngroup in $addngroups ; do
+					IFS="="
+					set -- $addngroup; addngname="$1"; addngid="$2"
+					if [ -n "$addngid" ]; then
+						group_exists "$addngname" || group_add "$addngname" "$addngid"
+					else
+						group_add_next "$addngname"
+					fi
+
+					group_add_user "$addngname" "$uname"
+				done
+				IFS="$oIFS"
+			fi
+
+			unset uid gid uname gname addngroups addngroup addngname addngid
+		done
+	fi
+}
+
+update_alternatives() {
+	local root="${IPKG_INSTROOT}"
+	local action="$1"
+	local pkgname="$2"
+
+	if [ -f "$root/lib/apk/packages/${pkgname}.alternatives" ]; then
+		for pkg_alt in $(cat $root/lib/apk/packages/${pkgname}.alternatives); do
+			local best_prio=0;
+			local best_src="/bin/busybox";
+			pkg_prio=${pkg_alt%%:*};
+			pkg_target=${pkg_alt#*:};
+			pkg_target=${pkg_target%:*};
+			pkg_src=${pkg_alt##*:};
+
+			if [ -e "$root/$target" ]; then
+				for alts in $root/lib/apk/packages/*.alternatives; do
+					for alt in $(cat $alts); do
+						prio=${alt%%:*};
+						target=${alt#*:};
+						target=${target%:*};
+						src=${alt##*:};
+
+						if [ "$target" = "$pkg_target" ] &&
+						   [ "$src" != "$pkg_src" ] &&
+						   [ "$best_prio" -lt "$prio" ]; then
+							best_prio=$prio;
+							best_src=$src;
+						fi
+					done
+				done
+			fi
+			case "$action" in
+				install)
+					if [ "$best_prio" -lt "$pkg_prio" ]; then
+						ln -sf "$pkg_src" "$root/$pkg_target"
+						echo "add alternative: $pkg_target -> $pkg_src"
+					fi
+				;;
+				remove)
+					if [ "$best_prio" -lt "$pkg_prio" ]; then
+						ln -sf "$best_src" "$root/$pkg_target"
+						echo "add alternative: $pkg_target -> $best_src"
+					fi
+				;;
+			esac
+		done
+	fi
+}
+
+default_postinst() {
+	local root="${IPKG_INSTROOT}"
+	[ -z "$pkgname" ] && local pkgname="$(basename ${1%.*})"
+	local filelist="${root}/usr/lib/opkg/info/${pkgname}.list"
+	[ -f "$root/lib/apk/packages/${pkgname}.list" ] && filelist="$root/lib/apk/packages/${pkgname}.list"
+	local ret=0
+
+	if [ -e "${root}/usr/lib/opkg/info/${pkgname}.list" ]; then
+		filelist="${root}/usr/lib/opkg/info/${pkgname}.list"
+		add_group_and_user "${pkgname}"
+	fi
+
+	if [ -e "${root}/lib/apk/packages/${pkgname}.list" ]; then
+		filelist="${root}/lib/apk/packages/${pkgname}.list"
+		update_alternatives install "${pkgname}"
+	fi
+
+	if [ -d "$root/rootfs-overlay" ]; then
+		cp -R $root/rootfs-overlay/. $root/
+		rm -fR $root/rootfs-overlay/
+	fi
+
+	if [ -z "$root" ]; then
+		if grep -m1 -q -s "^/etc/modules.d/" "$filelist"; then
+			kmodloader
+		fi
+
+		if grep -m1 -q -s "^/etc/sysctl.d/" "$filelist"; then
+			/etc/init.d/sysctl restart
+		fi
+
+		if grep -m1 -q -s "^/etc/uci-defaults/" "$filelist"; then
+			[ -d /tmp/.uci ] || mkdir -p /tmp/.uci
+			for i in $(grep -s "^/etc/uci-defaults/" "$filelist"); do
+				( [ -f "$i" ] && cd "$(dirname $i)" && . "$i" ) && rm -f "$i"
+			done
+			uci commit
+		fi
+
+		rm -f /tmp/luci-indexcache
+	fi
+
+	if [ -f "$root/usr/lib/opkg/info/${pkgname}.postinst-pkg" ]; then
+		( . "$root/usr/lib/opkg/info/${pkgname}.postinst-pkg" )
+		ret=$?
+	fi
+
+	local shell="$(command -v bash)"
+	for i in $(grep -s "^/etc/init.d/" "$filelist"); do
+		if [ -n "$root" ]; then
+			${shell:-/bin/sh} "$root/etc/rc.common" "$root$i" enable
+		else
+			if [ "$PKG_UPGRADE" != "1" ]; then
+				"$i" enable
+			fi
+			"$i" start
+		fi
+	done
+
+	return $ret
+}
+
+include() {
+	local file
+
+	for file in $(ls $1/*.sh 2>/dev/null); do
+		. $file
+	done
+}
+
+ipcalc() {
+	set -- $(ipcalc.sh "$@")
+	[ $? -eq 0 ] && export -- "$@"
+}
+
+find_mtd_index() {
+	local PART="$(grep "\"$1\"" /proc/mtd | awk -F: '{print $1}')"
+	local INDEX="${PART##mtd}"
+
+	echo ${INDEX}
+}
+
+find_mtd_part() {
+	local INDEX=$(find_mtd_index "$1")
+	local PREFIX=/dev/mtdblock
+
+	[ -d /dev/mtdblock ] && PREFIX=/dev/mtdblock/
+	echo "${INDEX:+$PREFIX$INDEX}"
+}
+
+find_system_slot() {
+	sys=`cat /proc/cmdline | grep "system=a"`
+	if [ -z "$sys" ]; then
+		sys=`cat /proc/cmdline | grep "system=b"`
+			if [ -z "$sys" ]; then
+				type=""
+			else
+				type="-b"
+	fi
+	else
+		type="-a"
+	fi
+	echo ${type}
+}
+
+find_mmc_part() {
+	local DEVNAME PARTNAME ROOTDEV
+
+	if grep -q "$1" /proc/mtd; then
+		echo "" && return 0
+	fi
+
+	if [ -n "$2" ]; then
+		ROOTDEV="$2"
+	else
+		ROOTDEV="mmcblk*"
+	fi
+
+	for DEVNAME in /sys/block/$ROOTDEV/mmcblk*p*; do
+		PARTNAME="$(grep PARTNAME ${DEVNAME}/uevent | cut -f2 -d'=')"
+		[ "$PARTNAME" = "$1" ] && echo "/dev/$(basename $DEVNAME)" && return 0
+	done
+}
+
+group_add() {
+	local name="$1"
+	local gid="$2"
+	local rc
+	[ -f "${IPKG_INSTROOT}/etc/group" ] || return 1
+	[ -n "$IPKG_INSTROOT" ] || lock /var/lock/group
+	echo "${name}:x:${gid}:" >> ${IPKG_INSTROOT}/etc/group
+	[ -n "$IPKG_INSTROOT" ] || lock -u /var/lock/group
+}
+
+group_exists() {
+	grep -qs "^${1}:" ${IPKG_INSTROOT}/etc/group
+}
+
+group_add_next() {
+	local gid gids
+	gid=$(grep -s "^${1}:" ${IPKG_INSTROOT}/etc/group | cut -d: -f3)
+	if [ -n "$gid" ]; then
+		echo $gid
+		return
+	fi
+	gids=$(cut -d: -f3 ${IPKG_INSTROOT}/etc/group)
+	gid=32768
+	while echo "$gids" | grep -q "^$gid$"; do
+		gid=$((gid + 1))
+	done
+	group_add $1 $gid
+	echo $gid
+}
+
+group_add_user() {
+	local grp delim=","
+	grp=$(grep -s "^${1}:" ${IPKG_INSTROOT}/etc/group)
+	echo "$grp" | cut -d: -f4 | grep -q $2 && return
+	echo "$grp" | grep -q ":$" && delim=""
+	[ -n "$IPKG_INSTROOT" ] || lock /var/lock/passwd
+	sed -i "s/$grp/$grp$delim$2/g" ${IPKG_INSTROOT}/etc/group
+	if [ -z "$IPKG_INSTROOT" ] && [ -x /usr/sbin/selinuxenabled ] && selinuxenabled; then
+		restorecon /etc/group
+	fi
+	[ -n "$IPKG_INSTROOT" ] || lock -u /var/lock/passwd
+}
+
+user_add() {
+	local name="${1}"
+	local uid="${2}"
+	local gid="${3}"
+	local desc="${4:-$1}"
+	local home="${5:-/var/run/$1}"
+	local shell="${6:-/bin/false}"
+	local rc
+	[ -z "$uid" ] && {
+		uids=$(cut -d: -f3 ${IPKG_INSTROOT}/etc/passwd)
+		uid=32768
+		while echo "$uids" | grep -q "^$uid$"; do
+			uid=$((uid + 1))
+		done
+	}
+	[ -z "$gid" ] && gid=$uid
+	[ -f "${IPKG_INSTROOT}/etc/passwd" ] || return 1
+	[ -n "$IPKG_INSTROOT" ] || lock /var/lock/passwd
+	echo "${name}:x:${uid}:${gid}:${desc}:${home}:${shell}" >> ${IPKG_INSTROOT}/etc/passwd
+	echo "${name}:x:0:0:99999:7:::" >> ${IPKG_INSTROOT}/etc/shadow
+	[ -n "$IPKG_INSTROOT" ] || lock -u /var/lock/passwd
+}
+
+user_exists() {
+	grep -qs "^${1}:" ${IPKG_INSTROOT}/etc/passwd
+}
+
+board_name() {
+	[ -e /tmp/sysinfo/board_name ] && cat /tmp/sysinfo/board_name || echo "generic"
+}
+
+cmdline_get_var() {
+	local var=$1
+	local cmdlinevar tmp
+
+	for cmdlinevar in $(cat /proc/cmdline); do
+		tmp=${cmdlinevar##${var}}
+		[ "=" = "${tmp:0:1}" ] && echo ${tmp:1}
+	done
+}
+
+[ -z "$IPKG_INSTROOT" ] && [ -f /lib/config/uci.sh ] && . /lib/config/uci.sh || true
diff --git a/package/base-files/files/lib/functions/caldata.sh b/package/base-files/files/lib/functions/caldata.sh
new file mode 100644
index 0000000..f0fc907
--- /dev/null
+++ b/package/base-files/files/lib/functions/caldata.sh
@@ -0,0 +1,218 @@
+# Copyright (C) 2019 OpenWrt.org
+
+. /lib/functions.sh
+. /lib/functions/system.sh
+
+caldata_dd() {
+	local source=$1
+	local target=$2
+	local count=$(($3))
+	local offset=$(($4))
+
+	dd if=$source of=$target iflag=skip_bytes,fullblock bs=$count skip=$offset count=1 2>/dev/null
+	return $?
+}
+
+caldata_die() {
+	echo "caldata: " "$*"
+	exit 1
+}
+
+caldata_extract() {
+	local part=$1
+	local offset=$(($2))
+	local count=$(($3))
+	local mtd
+
+	mtd=$(find_mtd_chardev $part)
+	[ -n "$mtd" ] || caldata_die "no mtd device found for partition $part"
+
+	caldata_dd $mtd /lib/firmware/$FIRMWARE $count $offset || \
+		caldata_die "failed to extract calibration data from $mtd"
+}
+
+caldata_extract_ubi() {
+	local part=$1
+	local offset=$(($2))
+	local count=$(($3))
+	local ubidev
+	local ubi
+
+	. /lib/upgrade/nand.sh
+
+	ubidev=$(nand_find_ubi $CI_UBIPART)
+	ubi=$(nand_find_volume $ubidev $part)
+	[ -n "$ubi" ] || caldata_die "no UBI volume found for $part"
+
+	caldata_dd /dev/$ubi /lib/firmware/$FIRMWARE $count $offset || \
+		caldata_die "failed to extract calibration data from $ubi"
+}
+
+caldata_extract_mmc() {
+	local part=$1
+	local offset=$(($2))
+	local count=$(($3))
+	local mmc_part
+
+	mmc_part=$(find_mmc_part $part)
+	[ -n "$mmc_part" ] || caldata_die "no mmc partition found for partition $part"
+
+	caldata_dd $mmc_part /lib/firmware/$FIRMWARE $count $offset || \
+		caldata_die "failed to extract calibration data from $mmc_part"
+}
+
+caldata_extract_reverse() {
+	local part=$1
+	local offset=$2
+	local count=$(($3))
+	local mtd
+	local reversed
+	local caldata
+
+	mtd=$(find_mtd_chardev "$part")
+	reversed=$(hexdump -v -s $offset -n $count -e '1/1 "%02x "' $mtd)
+
+	for byte in $reversed; do
+		caldata="\x${byte}${caldata}"
+	done
+
+	printf "%b" "$caldata" > /lib/firmware/$FIRMWARE
+}
+
+caldata_from_file() {
+	local source=$1
+	local offset=$(($2))
+	local count=$(($3))
+	local target=$4
+
+	[ -n "$target" ] || target=/lib/firmware/$FIRMWARE
+
+	caldata_dd $source $target $count $offset || \
+		caldata_die "failed to extract calibration data from $source"
+}
+
+caldata_sysfsload_from_file() {
+	local source=$1
+	local offset=$(($2))
+	local count=$(($3))
+	local target_dir="/sys/$DEVPATH"
+	local target="$target_dir/data"
+
+	[ -d "$target_dir" ] || \
+		caldata_die "no sysfs dir to write: $target"
+
+	echo 1 > "$target_dir/loading"
+	caldata_dd $source $target $count $offset
+	if [ $? != 0 ]; then
+		echo 1 > "$target_dir/loading"
+		caldata_die "failed to extract calibration data from $source"
+	else
+		echo 0 > "$target_dir/loading"
+	fi
+}
+
+caldata_valid() {
+	local expected="$1"
+	local target=$2
+
+	[ -n "$target" ] || target=/lib/firmware/$FIRMWARE
+
+	magic=$(hexdump -v -n 2 -e '1/1 "%02x"' $target)
+	[ "$magic" = "$expected" ]
+	return $?
+}
+
+caldata_patch_data() {
+	local data=$1
+	local data_count=$((${#1} / 2))
+	[ -n "$2" ] && local data_offset=$(($2))
+	[ -n "$3" ] && local chksum_offset=$(($3))
+	local target=$4
+	local fw_data
+	local fw_chksum
+
+	[ -z "$data" -o -z "$data_offset" ] && return
+
+	[ -n "$target" ] || target=/lib/firmware/$FIRMWARE
+
+	fw_data=$(hexdump -v -n $data_count -s $data_offset -e '1/1 "%02x"' $target)
+
+	if [ "$data" != "$fw_data" ]; then
+
+		if [ -n "$chksum_offset" ]; then
+			fw_chksum=$(hexdump -v -n 2 -s $chksum_offset -e '1/1 "%02x"' $target)
+			fw_chksum=$(xor $fw_chksum $(data_2xor_val $fw_data) $(data_2xor_val $data))
+
+			data_2bin $fw_chksum | \
+				dd of=$target conv=notrunc bs=1 seek=$chksum_offset count=2 || \
+				caldata_die "failed to write chksum to eeprom file"
+		fi
+
+		data_2bin $data | \
+			dd of=$target conv=notrunc bs=1 seek=$data_offset count=$data_count || \
+			caldata_die "failed to write data to eeprom file"
+	fi
+}
+
+ath9k_patch_mac() {
+	local mac=$1
+	local target=$2
+
+	caldata_patch_data "${mac//:/}" 0x2 "" "$target"
+}
+
+ath9k_patch_mac_crc() {
+	local mac=$1
+	local mac_offset=$2
+	local chksum_offset=$((mac_offset - 10))
+	local target=$4
+
+	caldata_patch_data "${mac//:/}" "$mac_offset" "$chksum_offset" "$target"
+}
+
+ath10k_patch_mac() {
+	local mac=$1
+	local target=$2
+
+	caldata_patch_data "${mac//:/}" 0x6 0x2 "$target"
+}
+
+ath11k_patch_mac() {
+	local mac=$1
+	# mac_id from 0 to 5
+	local mac_id=$2
+	local target=$3
+
+	[ -z "$mac_id" ] && return
+
+	caldata_patch_data "${mac//:/}" $(printf "0x%x" $(($mac_id * 0x6 + 0xe))) 0xa "$target"
+}
+
+ath10k_remove_regdomain() {
+	local target=$1
+
+	caldata_patch_data "0000" 0xc 0x2 "$target"
+}
+
+ath11k_remove_regdomain() {
+	local target=$1
+	local regdomain
+	local regdomain_data
+
+	regdomain=$(hexdump -v -n 2 -s 0x34 -e '1/1 "%02x"' $target)
+	caldata_patch_data "0000" 0x34 0xa "$target"
+	
+	for offset in 0x450 0x458 0x500 0x5a8; do
+		regdomain_data=$(hexdump -v -n 2 -s $offset -e '1/1 "%02x"' $target)
+
+		if [ "$regdomain" == "$regdomain_data" ]; then
+			caldata_patch_data "0000" $offset 0xa "$target"
+		fi
+	done
+}
+
+ath11k_set_macflag() {
+	local target=$1
+
+	caldata_patch_data "0100" 0x3e 0xa "$target"
+}
diff --git a/package/base-files/files/lib/functions/ipv4.sh b/package/base-files/files/lib/functions/ipv4.sh
new file mode 100644
index 0000000..d0b93db
--- /dev/null
+++ b/package/base-files/files/lib/functions/ipv4.sh
@@ -0,0 +1,268 @@
+uint_max=4294967295
+
+d_10_0_0_0=167772160
+d_10_255_255_255=184549375
+
+d_172_16_0_0=2886729728
+d_172_31_255_255=2887778303
+
+d_192_168_0_0=3232235520
+d_192_168_255_255=3232301055
+
+d_169_254_0_0=2851995648
+d_169_254_255_255=2852061183
+
+d_127_0_0_0=2130706432
+d_127_255_255_255=2147483647
+
+d_224_0_0_0=3758096384
+d_239_255_255_255=4026531839
+
+# check that $1 is only base 10 digits, and that it doesn't
+# exceed 2^32-1
+assert_uint32() {
+    local __n="$1"
+
+    if [ -z "$__n" -o -n "${__n//[0-9]/}" ]; then
+	printf "Not a decimal integer (%s)\n" "$__n ">&2
+	return 1
+    fi
+
+    if [ "$__n" -gt $uint_max ]; then
+	printf "Out of range (%s)\n" "$__n" >&2
+	return 1
+    fi
+
+    if [ "$((__n + 0))" != "$__n" ]; then
+	printf "Not normalized notation (%s)\n" "$__n" >&2
+	return 1
+    fi
+
+    return 0
+}
+
+# return a count of the number of bits set in $1
+bitcount() {
+    local __var="$1" __c="$2"
+    assert_uint32 "$__c" || return 1
+
+    __c=$((((__c >> 1) & 0x55555555) + (__c & 0x55555555)))
+    __c=$((((__c >> 2) & 0x33333333) + (__c & 0x33333333)))
+    __c=$((((__c >> 4) & 0x0f0f0f0f) + (__c & 0x0f0f0f0f)))
+    __c=$((((__c >> 8) & 0x00ff00ff) + (__c & 0x00ff00ff)))
+    __c=$((((__c >> 16) & 0x0000ffff) + (__c & 0x0000ffff)))
+
+    export -- "$__var=$__c"
+}
+
+# tedious but portable with busybox's limited shell
+# we check each octet to be in the range of 0..255,
+# and also make sure there's no extaneous characters.
+str2ip() {
+    local __var="$1" __ip="$2" __n __val=0
+
+    case "$__ip" in
+    [0-9].*)
+	__n="${__ip:0:1}"
+	__ip="${__ip:2}"
+	;;
+    [1-9][0-9].*)
+	__n="${__ip:0:2}"
+	__ip="${__ip:3}"
+	;;
+    1[0-9][0-9].*|2[0-4][0-9].*|25[0-5].*)
+	__n="${__ip:0:3}"
+	__ip="${__ip:4}"
+	;;
+    *)
+	printf "Not a dotted quad (%s)\n" "$2" >&2
+	return 1
+	;;
+    esac
+
+    __val=$((__n << 24))
+
+    case "$__ip" in
+    [0-9].*)
+	__n="${__ip:0:1}"
+	__ip="${__ip:2}"
+	;;
+    [1-9][0-9].*)
+	__n="${__ip:0:2}"
+	__ip="${__ip:3}"
+	;;
+    1[0-9][0-9].*|2[0-4][0-9].*|25[0-5].*)
+	__n="${__ip:0:3}"
+	__ip="${__ip:4}"
+	;;
+    *)
+	printf "Not a dotted quad (%s)\n" "$2" >&2
+	return 1
+	;;
+    esac
+
+    __val=$((__val + (__n << 16)))
+
+    case "$__ip" in
+    [0-9].*)
+	__n="${__ip:0:1}"
+	__ip="${__ip:2}"
+	;;
+    [1-9][0-9].*)
+	__n="${__ip:0:2}"
+	__ip="${__ip:3}"
+	;;
+    1[0-9][0-9].*|2[0-4][0-9].*|25[0-5].*)
+	__n="${__ip:0:3}"
+	__ip="${__ip:4}"
+	;;
+    *)
+	printf "Not a dotted quad (%s)\n" "$2" >&2
+	return 1
+	;;
+    esac
+
+    __val=$((__val + (__n << 8)))
+
+    case "$__ip" in
+    [0-9])
+	__n="${__ip:0:1}"
+	__ip="${__ip:1}"
+	;;
+    [1-9][0-9])
+	__n="${__ip:0:2}"
+	__ip="${__ip:2}"
+	;;
+    1[0-9][0-9]|2[0-4][0-9]|25[0-5])
+	__n="${__ip:0:3}"
+	__ip="${__ip:3}"
+	;;
+    *)
+	printf "Not a dotted quad (%s)\n" "$2" >&2
+	return 1
+	;;
+    esac
+
+    __val=$((__val + __n))
+
+    if [ -n "$__ip" ]; then
+	printf "Not a dotted quad (%s)\n" "$2" >&2
+	return 1
+    fi
+
+    export -- "$__var=$__val"
+    return 0
+}
+
+# convert back from an integer to dotted-quad.
+ip2str() {
+    local __var="$1" __n="$2"
+    assert_uint32 "$__n" || return 1
+
+    export -- "$__var=$((__n >> 24)).$(((__n >> 16) & 255)).$(((__n >> 8) & 255)).$((__n & 255))"
+}
+
+# convert prefix into an integer bitmask
+prefix2netmask() {
+    local __var="$1" __n="$2"
+    assert_uint32 "$__n" || return 1
+
+    if [ "$__n" -gt 32 ]; then
+	printf "Prefix out-of-range (%s)" "$__n" >&2
+	return 1
+    fi
+
+    export -- "$__var=$(((~(uint_max >> __n)) & uint_max))"
+}
+
+_is_contiguous() {
+    local __x="$1"	# no checking done
+    local __y=$((~__x & uint_max))
+    local __z=$(((__y + 1) & uint_max))
+
+    [ $((__z & __y)) -eq 0 ]
+}
+
+# check argument as being contiguous upper bits (and yes,
+# 0 doesn't have any discontiguous bits).
+is_contiguous() {
+    local __var="$1" __x="$2" __val=0
+    assert_uint32 "$__x" || return 1
+
+    local __y=$((~__x & uint_max))
+    local __z=$(((__y + 1) & uint_max))
+
+    [ $((__z & __y)) -eq 0 ] && __val=1
+
+    export -- "$__var=$__val"
+}
+
+# convert mask to prefix, validating that it's a conventional
+# (contiguous) netmask.
+netmask2prefix() {
+    local __var="$1" __n="$2" __cont __bits
+    assert_uint32 "$__n" || return 1
+
+    is_contiguous __cont "$__n" || return 1
+    if [ $__cont -eq 0 ]; then
+	printf "Not a contiguous netmask (%08x)\n" "$__n" >&2
+	return 1
+    fi
+
+    bitcount __bits "$__n"		# already checked
+
+    export -- "$__var=$__bits"
+}
+
+# check the argument as being an rfc-1918 address
+is_rfc1918() {
+    local __var="$1" __x="$2" __val=0
+    assert_uint32 "$__x" || return 1
+
+    if [ $d_10_0_0_0 -le $__x ] && [ $__x -le $d_10_255_255_255 ]; then
+	__val=1
+    elif [ $d_172_16_0_0 -le $__x ] && [ $__x -le $d_172_31_255_255 ]; then
+	__val=1
+    elif [ $d_192_168_0_0 -le $__x ] && [ $__x -le $d_192_168_255_255 ]; then
+	__val=1
+    fi
+
+    export -- "$__var=$__val"
+}
+
+# check the argument as being an rfc-3927 address
+is_rfc3927() {
+    local __var="$1" __x="$2" __val=0
+    assert_uint32 "$__x" || return 1
+
+    if [ $d_169_254_0_0 -le $__x ] && [ $__x -le $d_169_254_255_255 ]; then
+	__val=1
+    fi
+
+    export -- "$__var=$__val"
+}
+
+# check the argument as being an rfc-1122 loopback address
+is_loopback() {
+    local __var="$1" __x="$2" __val=0
+    assert_uint32 "$__x" || return 1
+
+    if [ $d_127_0_0_0 -le $__x ] && [ $__x -le $d_127_255_255_255 ]; then
+	__val=1
+    fi
+
+    export -- "$__var=$__val"
+}
+
+# check the argument as being a multicast address
+is_multicast() {
+    local __var="$1" __x="$2" __val=0
+    assert_uint32 "$__x" || return 1
+
+    if [ $d_224_0_0_0 -le $__x ] && [ $__x -le $d_239_255_255_255 ]; then
+	__val=1
+    fi
+
+    export -- "$__var=$__val"
+}
+
diff --git a/package/base-files/files/lib/functions/leds.sh b/package/base-files/files/lib/functions/leds.sh
new file mode 100644
index 0000000..333d900
--- /dev/null
+++ b/package/base-files/files/lib/functions/leds.sh
@@ -0,0 +1,125 @@
+# Copyright (C) 2013 OpenWrt.org
+
+get_dt_led_path() {
+	local ledpath
+	local basepath="/proc/device-tree"
+	local nodepath="$basepath/aliases/led-$1"
+
+	[ -f "$nodepath" ] && ledpath=$(cat "$nodepath")
+	[ -n "$ledpath" ] && ledpath="$basepath$ledpath"
+
+	echo "$ledpath"
+}
+
+get_dt_led_color_func() {
+	local enum
+	local func
+	local idx
+	local label
+
+	[ -e "$1/function" ] && func=$(cat "$1/function")
+	[ -e "$1/color" ] && idx=$((0x$(hexdump -n 4 -e '4/1 "%02x"' "$1/color")))
+	[ -e "$1/function-enumerator" ] && \
+		enum=$((0x$(hexdump -n 4 -e '4/1 "%02x"' "$1/function-enumerator")))
+
+	[ -z "$idx" ] && [ -z "$func" ] && return 2
+
+	if [ -n "$idx" ]; then
+		for color in "white" "red" "green" "blue" "amber" \
+			     "violet" "yellow" "ir" "multicolor" "rgb" \
+			     "purple" "orange" "pink" "cyan" "lime"
+		do
+			[ $idx -eq 0 ] && label="$color" && break
+			idx=$((idx-1))
+		done
+	fi
+
+	label="$label:$func"
+	[ -n "$enum" ] && label="$label-$enum"
+	echo "$label"
+
+	return 0
+}
+
+get_dt_led() {
+	local label
+	local ledpath=$(get_dt_led_path $1)
+
+	[ -n "$ledpath" ] && \
+		label=$(cat "$ledpath/label" 2>/dev/null) || \
+		label=$(cat "$ledpath/chan-name" 2>/dev/null) || \
+		label=$(get_dt_led_color_func "$ledpath") || \
+		label=$(basename "$ledpath")
+
+	echo "$label"
+}
+
+led_set_attr() {
+	[ -f "/sys/class/leds/$1/$2" ] && echo "$3" > "/sys/class/leds/$1/$2"
+}
+
+led_timer() {
+	led_set_attr $1 "trigger" "timer"
+	led_set_attr $1 "delay_on" "$2"
+	led_set_attr $1 "delay_off" "$3"
+}
+
+led_on() {
+	led_set_attr $1 "trigger" "none"
+	led_set_attr $1 "brightness" 255
+}
+
+led_off() {
+	led_set_attr $1 "trigger" "none"
+	led_set_attr $1 "brightness" 0
+}
+
+status_led_restore_trigger() {
+	local trigger
+	local ledpath=$(get_dt_led_path $1)
+
+	[ -n "$ledpath" ] && \
+		trigger=$(cat "$ledpath/linux,default-trigger" 2>/dev/null)
+
+	[ -n "$trigger" ] && \
+		led_set_attr "$(get_dt_led $1)" "trigger" "$trigger"
+}
+
+status_led_set_timer() {
+	led_timer $status_led "$1" "$2"
+	[ -n "$status_led2" ] && led_timer $status_led2 "$1" "$2"
+}
+
+status_led_set_heartbeat() {
+	led_set_attr $status_led "trigger" "heartbeat"
+}
+
+status_led_on() {
+	led_on $status_led
+	[ -n "$status_led2" ] && led_on $status_led2
+}
+
+status_led_off() {
+	led_off $status_led
+	[ -n "$status_led2" ] && led_off $status_led2
+}
+
+status_led_blink_slow() {
+	led_timer $status_led 1000 1000
+}
+
+status_led_blink_fast() {
+	led_timer $status_led 100 100
+}
+
+status_led_blink_preinit() {
+	led_timer $status_led 100 100
+}
+
+status_led_blink_failsafe() {
+	led_timer $status_led 50 50
+}
+
+status_led_blink_preinit_regular() {
+	led_timer $status_led 200 200
+}
diff --git a/package/base-files/files/lib/functions/migrations.sh b/package/base-files/files/lib/functions/migrations.sh
new file mode 100644
index 0000000..d43ea35
--- /dev/null
+++ b/package/base-files/files/lib/functions/migrations.sh
@@ -0,0 +1,67 @@
+. /lib/functions.sh
+
+migrate_led_sysfs() {
+	local cfg="$1"; shift
+	local tuples="$@"
+	local sysfs
+	local name
+
+	config_get sysfs ${cfg} sysfs
+	config_get name ${cfg} name
+
+	[ -z "${sysfs}" ] && return
+
+	for tuple in ${tuples}; do
+		local old=${tuple%=*}
+		local new=${tuple#*=}
+		local new_sysfs
+
+		new_sysfs=$(echo ${sysfs} | sed "s/${old}/${new}/")
+
+		[ "${new_sysfs}" = "${sysfs}" ] && continue
+
+		uci set system.${cfg}.sysfs="${new_sysfs}"
+
+		logger -t led-migration "sysfs option of LED \"${name}\" updated to ${new_sysfs}"
+	done;
+}
+
+remove_devicename_led_sysfs() {
+	local cfg="$1"; shift
+	local exceptions="$@"
+	local sysfs
+	local name
+	local new_sysfs
+
+	config_get sysfs ${cfg} sysfs
+	config_get name ${cfg} name
+
+	# only continue if two or more colons are present
+	echo "${sysfs}" | grep -q ":.*:" || return
+
+	for exception in ${exceptions}; do
+		# no change if exceptions provided as argument are found for devicename
+		echo "${sysfs}" | grep -q "^${exception}:" && return
+	done
+
+	new_sysfs=$(echo ${sysfs} | sed "s/^[^:]*://")
+
+	uci set system.${cfg}.sysfs="${new_sysfs}"
+
+	logger -t led-migration "sysfs option of LED \"${name}\" updated to ${new_sysfs}"
+}
+
+migrate_leds() {
+	config_load system
+	config_foreach migrate_led_sysfs led "$@"
+}
+
+remove_devicename_leds() {
+	config_load system
+	config_foreach remove_devicename_led_sysfs led "$@"
+}
+
+migrations_apply() {
+	local realm="$1"
+	[ -n "$(uci changes ${realm})" ] && uci -q commit ${realm}
+}
diff --git a/package/base-files/files/lib/functions/network.sh b/package/base-files/files/lib/functions/network.sh
new file mode 100644
index 0000000..4851a58
--- /dev/null
+++ b/package/base-files/files/lib/functions/network.sh
@@ -0,0 +1,325 @@
+# 1: destination variable
+# 2: interface
+# 3: path
+# 4: separator
+# 5: limit
+__network_ifstatus() {
+	local __tmp
+
+	[ -z "$__NETWORK_CACHE" ] && {
+		__tmp="$(ubus call network.interface dump 2>&1)"
+		case "$?" in
+			4) : ;;
+			0) export __NETWORK_CACHE="$__tmp" ;;
+			*) echo "$__tmp" >&2 ;;
+		esac
+	}
+
+	__tmp="$(jsonfilter ${4:+-F "$4"} ${5:+-l "$5"} -s "${__NETWORK_CACHE:-{}}" -e "$1=@.interface${2:+[@.interface='$2']}$3")"
+
+	[ -z "$__tmp" ] && \
+		unset "$1" && \
+		return 1
+
+	eval "$__tmp"
+}
+
+# determine first IPv4 address of given logical interface
+# 1: destination variable
+# 2: interface
+network_get_ipaddr() {
+	__network_ifstatus "$1" "$2" "['ipv4-address'][0].address";
+}
+
+# determine first IPv6 address of given logical interface
+# 1: destination variable
+# 2: interface
+network_get_ipaddr6() {
+	__network_ifstatus "$1" "$2" "['ipv6-address'][0].address" || \
+		__network_ifstatus "$1" "$2" "['ipv6-prefix-assignment'][0]['local-address'].address" || \
+		return 1
+}
+
+# determine first IPv4 subnet of given logical interface
+# 1: destination variable
+# 2: interface
+network_get_subnet() {
+	__network_ifstatus "$1" "$2" "['ipv4-address'][0]['address','mask']" "/"
+}
+
+# determine first IPv6 subnet of given logical interface
+# 1: destination variable
+# 2: interface
+network_get_subnet6() {
+	local __nets __addr
+
+	if network_get_subnets6 __nets "$2"; then
+		# Attempt to return first non-fe80::/10, non-fc::/7 range
+		for __addr in $__nets; do
+			case "$__addr" in fe[8ab]?:*|f[cd]??:*)
+				continue
+			esac
+			export "$1=$__addr"
+			return 0
+		done
+
+		# Attempt to return first non-fe80::/10 range
+		for __addr in $__nets; do
+			case "$__addr" in fe[8ab]?:*)
+				continue
+			esac
+			export "$1=$__addr"
+			return 0
+		done
+
+		# Return first item
+		for __addr in $__nets; do
+			export "$1=$__addr"
+			return 0
+		done
+	fi
+
+	unset "$1"
+	return 1
+}
+
+# determine first IPv6 prefix of given logical interface
+# 1: destination variable
+# 2: interface
+network_get_prefix6() {
+	__network_ifstatus "$1" "$2" "['ipv6-prefix'][0]['address','mask']" "/"
+}
+
+# determine first IPv6 prefix assignment of given logical interface
+# 1: destination variable
+# 2: interface
+network_get_prefix_assignment6() {
+	__network_ifstatus "$1" "$2" "['ipv6-prefix-assignment'][0]['address','mask']" "/"
+}
+
+# determine all IPv4 addresses of given logical interface
+# 1: destination variable
+# 2: interface
+network_get_ipaddrs() {
+	__network_ifstatus "$1" "$2" "['ipv4-address'][*].address"
+}
+
+# determine all IPv6 addresses of given logical interface
+# 1: destination variable
+# 2: interface
+network_get_ipaddrs6() {
+	local __addr
+	local __list=""
+
+	if __network_ifstatus "__addr" "$2" "['ipv6-address'][*].address"; then
+		for __addr in $__addr; do
+			__list="${__list:+$__list }${__addr}"
+		done
+	fi
+
+	if __network_ifstatus "__addr" "$2" "['ipv6-prefix-assignment'][*]['local-address'].address"; then
+		for __addr in $__addr; do
+			__list="${__list:+$__list }${__addr}"
+		done
+	fi
+
+	if [ -n "$__list" ]; then
+		export "$1=$__list"
+		return 0
+	fi
+
+	unset "$1"
+	return 1
+}
+
+# determine all IP addresses of given logical interface
+# 1: destination variable
+# 2: interface
+network_get_ipaddrs_all() {
+	local __addr __addr6
+
+	network_get_ipaddrs __addr "$2"
+	network_get_ipaddrs6 __addr6 "$2"
+
+	if [ -n "$__addr" -o -n "$__addr6" ]; then
+		export "$1=${__addr:+$__addr }$__addr6"
+		return 0
+	fi
+
+	unset "$1"
+	return 1
+}
+
+# determine all IPv4 subnets of given logical interface
+# 1: destination variable
+# 2: interface
+network_get_subnets() {
+	__network_ifstatus "$1" "$2" "['ipv4-address'][*]['address','mask']" "/ "
+}
+
+# determine all IPv6 subnets of given logical interface
+# 1: destination variable
+# 2: interface
+network_get_subnets6() {
+	local __addr __mask
+	local __list=""
+
+	if __network_ifstatus "__addr" "$2" "['ipv6-address'][*]['address','mask']" "/ "; then
+		for __addr in $__addr; do
+			__list="${__list:+$__list }${__addr}"
+		done
+	fi
+
+	if __network_ifstatus "__addr" "$2" "['ipv6-prefix-assignment'][*]['local-address'].address" && \
+	   __network_ifstatus "__mask" "$2" "['ipv6-prefix-assignment'][*].mask"; then
+		for __addr in $__addr; do
+			__list="${__list:+$__list }${__addr}/${__mask%% *}"
+			__mask="${__mask#* }"
+		done
+	fi
+
+	if [ -n "$__list" ]; then
+		export "$1=$__list"
+		return 0
+	fi
+
+	unset "$1"
+	return 1
+}
+
+# determine all IPv6 prefixes of given logical interface
+# 1: destination variable
+# 2: interface
+network_get_prefixes6() {
+	__network_ifstatus "$1" "$2" "['ipv6-prefix'][*]['address','mask']" "/ "
+}
+
+# determine all IPv6 prefix assignments of given logical interface
+# 1: destination variable
+# 2: interface
+network_get_prefix_assignments6() {
+	__network_ifstatus "$1" "$2" "['ipv6-prefix-assignment'][*]['address','mask']" "/ "
+}
+
+# determine IPv4 gateway of given logical interface
+# 1: destination variable
+# 2: interface
+# 3: consider inactive gateway if "true" (optional)
+network_get_gateway() {
+	__network_ifstatus "$1" "$2" ".route[@.target='0.0.0.0' && !@.table].nexthop" "" 1 && \
+		return 0
+
+	[ "$3" = 1 -o "$3" = "true" ] && \
+		__network_ifstatus "$1" "$2" ".inactive.route[@.target='0.0.0.0' && !@.table].nexthop" "" 1
+}
+
+# determine IPv6 gateway of given logical interface
+# 1: destination variable
+# 2: interface
+# 3: consider inactive gateway if "true" (optional)
+network_get_gateway6() {
+	__network_ifstatus "$1" "$2" ".route[@.target='::' && !@.table].nexthop" "" 1 && \
+		return 0
+
+	[ "$3" = 1 -o "$3" = "true" ] && \
+		__network_ifstatus "$1" "$2" ".inactive.route[@.target='::' && !@.table].nexthop" "" 1
+}
+
+# determine the DNS servers of the given logical interface
+# 1: destination variable
+# 2: interface
+# 3: consider inactive servers if "true" (optional)
+network_get_dnsserver() {
+	__network_ifstatus "$1" "$2" "['dns-server'][*]" && return 0
+
+	[ "$3" = 1 -o "$3" = "true" ] && \
+		__network_ifstatus "$1" "$2" ".inactive['dns-server'][*]"
+}
+
+# determine the domains of the given logical interface
+# 1: destination variable
+# 2: interface
+# 3: consider inactive domains if "true" (optional)
+network_get_dnssearch() {
+	__network_ifstatus "$1" "$2" "['dns-search'][*]" && return 0
+
+	[ "$3" = 1 -o "$3" = "true" ] && \
+		__network_ifstatus "$1" "$2" ".inactive['dns-search'][*]"
+}
+
+
+# 1: destination variable
+# 2: addr
+# 3: inactive
+__network_wan()
+{
+	__network_ifstatus "$1" "" \
+		"[@.route[@.target='$2' && !@.table]].interface" "" 1 && \
+			return 0
+
+	[ "$3" = 1 -o "$3" = "true" ] && \
+		__network_ifstatus "$1" "" \
+			"[@.inactive.route[@.target='$2' && !@.table]].interface" "" 1
+}
+
+# find the logical interface which holds the current IPv4 default route
+# 1: destination variable
+# 2: consider inactive default routes if "true" (optional)
+network_find_wan() { __network_wan "$1" "0.0.0.0" "$2"; }
+
+# find the logical interface which holds the current IPv6 default route
+# 1: destination variable
+# 2: consider inactive default routes if "true" (optional)
+network_find_wan6() { __network_wan "$1" "::" "$2"; }
+
+# test whether the given logical interface is running
+# 1: interface
+network_is_up()
+{
+	local __up
+	__network_ifstatus "__up" "$1" ".up" && [ "$__up" = 1 ]
+}
+
+# determine the protocol of the given logical interface
+# 1: destination variable
+# 2: interface
+network_get_protocol() { __network_ifstatus "$1" "$2" ".proto"; }
+
+# determine the uptime of the given logical interface
+# 1: destination variable
+# 2: interface
+network_get_uptime() { __network_ifstatus "$1" "$2" ".uptime"; }
+
+# determine the metric of the given logical interface
+# 1: destination variable
+# 2: interface
+network_get_metric() { __network_ifstatus "$1" "$2" ".metric"; }
+
+# determine the layer 3 linux network device of the given logical interface
+# 1: destination variable
+# 2: interface
+network_get_device() { __network_ifstatus "$1" "$2" ".l3_device"; }
+
+# determine the layer 2 linux network device of the given logical interface
+# 1: destination variable
+# 2: interface
+network_get_physdev() { __network_ifstatus "$1" "$2" ".device"; }
+
+# defer netifd actions on the given linux network device
+# 1: device name
+network_defer_device()
+{
+	ubus call network.device set_state \
+		"$(printf '{ "name": "%s", "defer": true }' "$1")" 2>/dev/null
+}
+
+# continue netifd actions on the given linux network device
+# 1: device name
+network_ready_device()
+{
+	ubus call network.device set_state \
+		"$(printf '{ "name": "%s", "defer": false }' "$1")" 2>/dev/null
+}
+
+# flush the internal value cache to force re-reading values from ubus
+network_flush_cache() { unset __NETWORK_CACHE; }
diff --git a/package/base-files/files/lib/functions/preinit.sh b/package/base-files/files/lib/functions/preinit.sh
new file mode 100644
index 0000000..591e810
--- /dev/null
+++ b/package/base-files/files/lib/functions/preinit.sh
@@ -0,0 +1,87 @@
+# Copyright (C) 2006-2013 OpenWrt.org
+# Copyright (C) 2010 Vertical Communications
+
+boot_hook_splice_start() {
+	export -n PI_HOOK_SPLICE=1
+}
+
+boot_hook_splice_finish() {
+	local hook
+	for hook in $PI_STACK_LIST; do
+		local v; eval "v=\${${hook}_splice:+\$${hook}_splice }$hook"
+		export -n "${hook}=${v% }"
+		export -n "${hook}_splice="
+	done
+	export -n PI_HOOK_SPLICE=
+}
+
+boot_hook_init() {
+	local hook="${1}_hook"
+	export -n "PI_STACK_LIST=${PI_STACK_LIST:+$PI_STACK_LIST }$hook"
+	export -n "$hook="
+}
+
+boot_hook_add() {
+	local hook="${1}_hook${PI_HOOK_SPLICE:+_splice}"
+	local func="${2}"
+
+	[ -n "$func" ] && {
+		local v; eval "v=\$$hook"
+		export -n "$hook=${v:+$v }$func"
+	}
+}
+
+boot_hook_shift() {
+	local hook="${1}_hook"
+	local rvar="${2}"
+
+	local v; eval "v=\$$hook"
+	[ -n "$v" ] && {
+		local first="${v%% *}"
+
+		[ "$v" != "${v#* }" ] && \
+			export -n "$hook=${v#* }" || \
+			export -n "$hook="
+
+		export -n "$rvar=$first"
+		return 0
+	}
+
+	return 1
+}
+
+boot_run_hook() {
+	local hook="$1"
+	local func
+
+	while boot_hook_shift "$hook" func; do
+		local ran; eval "ran=\$PI_RAN_$func"
+		[ -n "$ran" ] || {
+			export -n "PI_RAN_$func=1"
+			$func "$1" "$2"
+		}
+	done
+}
+
+pivot() { # <new_root> <old_root>
+	/bin/mount -o noatime,move /proc $1/proc && \
+	pivot_root $1 $1$2 && {
+		/bin/mount -o noatime,move $2/dev /dev
+		/bin/mount -o noatime,move $2/tmp /tmp
+		/bin/mount -o noatime,move $2/sys /sys 2>&-
+		/bin/mount -o noatime,move $2/overlay /overlay 2>&-
+		return 0
+	}
+}
+
+fopivot() { # <rw_root> <work_dir> <ro_root> <dupe?>
+	/bin/mount -o noatime,lowerdir=/,upperdir=$1,workdir=$2 -t overlay "overlayfs:$1" /mnt
+	pivot /mnt $3
+}
+
+ramoverlay() {
+	mkdir -p /tmp/root
+	/bin/mount -t tmpfs -o noatime,mode=0755 root /tmp/root
+	mkdir -p /tmp/root/root /tmp/root/work
+	fopivot /tmp/root/root /tmp/root/work /rom 1
+}
diff --git a/package/base-files/files/lib/functions/service.sh b/package/base-files/files/lib/functions/service.sh
new file mode 100644
index 0000000..3d08e14
--- /dev/null
+++ b/package/base-files/files/lib/functions/service.sh
@@ -0,0 +1,103 @@
+#
+# service: simple wrapper around start-stop-daemon
+#
+# Usage: service ACTION EXEC ARGS...
+#
+# Action:
+#   -C	check if EXEC is alive
+#   -S	start EXEC, passing it ARGS as its arguments
+#   -K	kill EXEC, sending it a TERM signal if not specified otherwise
+#
+# Environment variables exposed:
+#   SERVICE_DAEMONIZE	run EXEC in background
+#   SERVICE_WRITE_PID	create a pid-file and use it for matching
+#   SERVICE_MATCH_EXEC	use EXEC command-line for matching (default)
+#   SERVICE_MATCH_NAME	use EXEC process name for matching
+#   SERVICE_USE_PID	assume EXEC create its own pid-file and use it for matching
+#   SERVICE_NAME	process name to use (default to EXEC file part)
+#   SERVICE_PID_FILE	pid file to use (default to /var/run/$SERVICE_NAME.pid)
+#   SERVICE_SIG		signal to send when using -K
+#   SERVICE_SIG_RELOAD	default signal used when reloading
+#   SERVICE_SIG_STOP	default signal used when stopping
+#   SERVICE_STOP_TIME	time to wait for a process to stop gracefully before killing it
+#   SERVICE_UID		user EXEC should be run as
+#   SERVICE_GID		group EXEC should be run as
+#
+#   SERVICE_DEBUG	don't do anything, but show what would be done
+#   SERVICE_QUIET	don't print anything
+#
+
+SERVICE_QUIET=1
+SERVICE_SIG_RELOAD="HUP"
+SERVICE_SIG_STOP="TERM"
+SERVICE_STOP_TIME=5
+SERVICE_MATCH_EXEC=1
+
+service() {
+	local ssd
+	local exec
+	local name
+	local start
+	ssd="${SERVICE_DEBUG:+echo }start-stop-daemon${SERVICE_QUIET:+ -q}"
+	case "$1" in
+	  -C)
+		ssd="$ssd -K -t"
+		;;
+	  -S)
+		ssd="$ssd -S${SERVICE_DAEMONIZE:+ -b}${SERVICE_WRITE_PID:+ -m}"
+		start=1
+		;;
+	  -K)
+		ssd="$ssd -K${SERVICE_SIG:+ -s $SERVICE_SIG}"
+		;;
+	  *)
+		echo "service: unknown ACTION '$1'" 1>&2
+		return 1
+	esac
+	shift
+	exec="$1"
+	[ -n "$exec" ] || {
+		echo "service: missing argument" 1>&2
+		return 1
+	}
+	[ -x "$exec" ] || {
+		echo "service: file '$exec' is not executable" 1>&2
+		return 1
+	}
+	name="${SERVICE_NAME:-${exec##*/}}"
+	[ -z "$SERVICE_USE_PID$SERVICE_WRITE_PID$SERVICE_PID_FILE" ] \
+		|| ssd="$ssd -p ${SERVICE_PID_FILE:-/var/run/$name.pid}"
+	[ -z "$SERVICE_MATCH_NAME" ] || ssd="$ssd -n $name"
+	ssd="$ssd${SERVICE_UID:+ -c $SERVICE_UID${SERVICE_GID:+:$SERVICE_GID}}"
+	[ -z "$SERVICE_MATCH_EXEC$start" ] || ssd="$ssd -x $exec"
+	shift
+	$ssd${1:+ -- "$@"}
+}
+
+service_check() {
+	service -C "$@"
+}
+
+service_signal() {
+	SERVICE_SIG="${SERVICE_SIG:-USR1}" service -K "$@"
+}
+
+service_start() {
+	service -S "$@"
+}
+
+service_stop() {
+	local try
+	SERVICE_SIG="${SERVICE_SIG:-$SERVICE_SIG_STOP}" service -K "$@" || return 1
+	while [ $((try++)) -lt $SERVICE_STOP_TIME ]; do
+		service -C "$@" || return 0
+		sleep 1
+	done
+	SERVICE_SIG="KILL" service -K "$@"
+	sleep 1
+	! service -C "$@"
+}
+
+service_reload() {
+	SERVICE_SIG="${SERVICE_SIG:-$SERVICE_SIG_RELOAD}" service -K "$@"
+}
diff --git a/package/base-files/files/lib/functions/system.sh b/package/base-files/files/lib/functions/system.sh
new file mode 100644
index 0000000..f43281b
--- /dev/null
+++ b/package/base-files/files/lib/functions/system.sh
@@ -0,0 +1,317 @@
+# Copyright (C) 2006-2013 OpenWrt.org
+
+. /lib/functions.sh
+. /usr/share/libubox/jshn.sh
+
+get_mac_binary() {
+	local path="$1"
+	local offset="$2"
+
+	if ! [ -e "$path" ]; then
+		echo "get_mac_binary: file $path not found!" >&2
+		return
+	fi
+
+	hexdump -v -n 6 -s $offset -e '5/1 "%02x:" 1/1 "%02x"' $path 2>/dev/null
+}
+
+get_mac_label_dt() {
+	local basepath="/proc/device-tree"
+	local macdevice="$(cat "$basepath/aliases/label-mac-device" 2>/dev/null)"
+	local macaddr
+
+	[ -n "$macdevice" ] || return
+
+	macaddr=$(get_mac_binary "$basepath/$macdevice/mac-address" 0 2>/dev/null)
+	[ -n "$macaddr" ] || macaddr=$(get_mac_binary "$basepath/$macdevice/local-mac-address" 0 2>/dev/null)
+
+	echo $macaddr
+}
+
+get_mac_label_json() {
+	local cfg="/etc/board.json"
+	local macaddr
+
+	[ -s "$cfg" ] || return
+
+	json_init
+	json_load "$(cat $cfg)"
+	if json_is_a system object; then
+		json_select system
+			json_get_var macaddr label_macaddr
+		json_select ..
+	fi
+
+	echo $macaddr
+}
+
+get_mac_label() {
+	local macaddr=$(get_mac_label_dt)
+
+	[ -n "$macaddr" ] || macaddr=$(get_mac_label_json)
+
+	echo $macaddr
+}
+
+find_mtd_chardev() {
+	local INDEX=$(find_mtd_index "$1")
+	local PREFIX=/dev/mtd
+
+	[ -d /dev/mtd ] && PREFIX=/dev/mtd/
+	echo "${INDEX:+$PREFIX$INDEX}"
+}
+
+get_mac_ascii() {
+	local part="$1"
+	local key="$2"
+	local mac_dirty
+
+	mac_dirty=$(strings "$part" | tr -d ' \t' | sed -n 's/^'"$key"'=//p' | head -n 1)
+
+	# "canonicalize" mac
+	[ -n "$mac_dirty" ] && macaddr_canonicalize "$mac_dirty"
+}
+
+mtd_get_mac_ascii() {
+	local mtdname="$1"
+	local key="$2"
+	local part
+
+	part=$(find_mtd_part "$mtdname")
+	if [ -z "$part" ]; then
+		echo "mtd_get_mac_ascii: partition $mtdname not found!" >&2
+		return
+	fi
+
+	get_mac_ascii "$part" "$key"
+}
+
+mtd_get_mac_encrypted_arcadyan() {
+	local iv="00000000000000000000000000000000"
+	local key="2A4B303D7644395C3B2B7053553C5200"
+	local mac_dirty
+	local mtdname="$1"
+	local part
+	local size
+
+	part=$(find_mtd_part "$mtdname")
+	if [ -z "$part" ]; then
+		echo "mtd_get_mac_encrypted_arcadyan: partition $mtdname not found!" >&2
+		return
+	fi
+
+	# Config decryption and getting mac. Trying uencrypt and openssl utils.
+	size=$((0x$(dd if=$part skip=9 bs=1 count=4 2>/dev/null | hexdump -v -e '1/4 "%08x"')))
+	if [[ -f  "/usr/bin/uencrypt" ]]; then
+		mac_dirty=$(dd if=$part bs=1 count=$size skip=$((0x100)) 2>/dev/null | \
+			uencrypt -d -n -k $key -i $iv | grep mac | cut -c 5-)
+	elif [[ -f  "/usr/bin/openssl" ]]; then
+		mac_dirty=$(dd if=$part bs=1 count=$size skip=$((0x100)) 2>/dev/null | \
+			openssl aes-128-cbc -d -nopad -K $key -iv $iv | grep mac | cut -c 5-)
+	else
+		echo "mtd_get_mac_encrypted_arcadyan: Neither uencrypt nor openssl was found!" >&2
+		return
+	fi
+
+	# "canonicalize" mac
+	[ -n "$mac_dirty" ] && macaddr_canonicalize "$mac_dirty"
+}
+
+mtd_get_mac_encrypted_deco() {
+	local mtdname="$1"
+
+	if ! [ -e "$mtdname" ]; then
+		echo "mtd_get_mac_encrypted_deco: file $mtdname not found!" >&2
+		return
+	fi
+
+	tplink_key="3336303032384339"
+
+	key=$(dd if=$mtdname bs=1 skip=16 count=8 2>/dev/null | \
+		uencrypt -n -d -k $tplink_key -c des-ecb | hexdump -v -n 8 -e '1/1 "%02x"')
+
+	macaddr=$(dd if=$mtdname bs=1 skip=32 count=8 2>/dev/null | \
+		uencrypt -n -d -k $key -c des-ecb | hexdump -v -n 6 -e '5/1 "%02x:" 1/1 "%02x"')
+
+	echo $macaddr
+}
+
+mtd_get_mac_uci_config_ubi() {
+	local volumename="$1"
+
+	. /lib/upgrade/nand.sh
+
+	local ubidev=$(nand_attach_ubi $CI_UBIPART)
+	local part=$(nand_find_volume $ubidev $volumename)
+
+	cat "/dev/$part" | sed -n 's/^\s*option macaddr\s*'"'"'\?\([0-9A-F:]\+\)'"'"'\?/\1/Ip'
+}
+
+mtd_get_mac_text() {
+	local mtdname="$1"
+	local offset=$((${2:-0}))
+	local length="${3:-17}"
+	local part
+
+	part=$(find_mtd_part "$mtdname")
+	if [ -z "$part" ]; then
+		echo "mtd_get_mac_text: partition $mtdname not found!" >&2
+		return
+	fi
+
+	[ $((offset + length)) -le $(mtd_get_part_size "$mtdname") ] || return
+
+	macaddr_canonicalize $(dd bs=1 if="$part" skip="$offset" count="$length" 2>/dev/null)
+}
+
+mtd_get_mac_binary() {
+	local mtdname="$1"
+	local offset="$2"
+	local part
+
+	part=$(find_mtd_part "$mtdname")
+	get_mac_binary "$part" "$offset"
+}
+
+mtd_get_mac_binary_ubi() {
+	local mtdname="$1"
+	local offset="$2"
+
+	. /lib/upgrade/nand.sh
+
+	local ubidev=$(nand_find_ubi $CI_UBIPART)
+	local part=$(nand_find_volume $ubidev $1)
+
+	get_mac_binary "/dev/$part" "$offset"
+}
+
+mtd_get_part_size() {
+	local part_name=$1
+	local first dev size erasesize name
+	while read dev size erasesize name; do
+		name=${name#'"'}; name=${name%'"'}
+		if [ "$name" = "$part_name" ]; then
+			echo $((0x$size))
+			break
+		fi
+	done < /proc/mtd
+}
+
+mmc_get_mac_ascii() {
+	local part_name="$1"
+	local key="$2"
+	local part
+
+	part=$(find_mmc_part "$part_name")
+	if [ -z "$part" ]; then
+		echo "mmc_get_mac_ascii: partition $part_name not found!" >&2
+		return
+	fi
+
+	get_mac_ascii "$part" "$key"
+}
+
+mmc_get_mac_binary() {
+	local part_name="$1"
+	local offset="$2"
+	local part
+
+	part=$(find_mmc_part "$part_name")
+	get_mac_binary "$part" "$offset"
+}
+
+macaddr_add() {
+	local mac=$1
+	local val=$2
+	local oui=${mac%:*:*:*}
+	local nic=${mac#*:*:*:}
+
+	nic=$(printf "%06x" $((0x${nic//:/} + val & 0xffffff)) | sed 's/^\(.\{2\}\)\(.\{2\}\)\(.\{2\}\)/\1:\2:\3/')
+	echo $oui:$nic
+}
+
+macaddr_generate_from_mmc_cid() {
+	local mmc_dev=$1
+
+	local sd_hash=$(sha256sum /sys/class/block/$mmc_dev/device/cid)
+	local mac_base=$(macaddr_canonicalize "$(echo "${sd_hash}" | dd bs=1 count=12 2>/dev/null)")
+	echo "$(macaddr_unsetbit_mc "$(macaddr_setbit_la "${mac_base}")")"
+}
+
+macaddr_geteui() {
+	local mac=$1
+	local sep=$2
+
+	echo ${mac:9:2}$sep${mac:12:2}$sep${mac:15:2}
+}
+
+macaddr_setbit() {
+	local mac=$1
+	local bit=${2:-0}
+
+	[ $bit -gt 0 -a $bit -le 48 ] || return
+
+	printf "%012x" $(( 0x${mac//:/} | 2**(48-bit) )) | sed -e 's/\(.\{2\}\)/\1:/g' -e 's/:$//'
+}
+
+macaddr_unsetbit() {
+	local mac=$1
+	local bit=${2:-0}
+
+	[ $bit -gt 0 -a $bit -le 48 ] || return
+
+	printf "%012x" $(( 0x${mac//:/} & ~(2**(48-bit)) )) | sed -e 's/\(.\{2\}\)/\1:/g' -e 's/:$//'
+}
+
+macaddr_setbit_la() {
+	macaddr_setbit $1 7
+}
+
+macaddr_unsetbit_mc() {
+	local mac=$1
+
+	printf "%02x:%s" $((0x${mac%%:*} & ~0x01)) ${mac#*:}
+}
+
+macaddr_random() {
+	local randsrc=$(get_mac_binary /dev/urandom 0)
+	
+	echo "$(macaddr_unsetbit_mc "$(macaddr_setbit_la "${randsrc}")")"
+}
+
+macaddr_canonicalize() {
+	local mac="$1"
+	local canon=""
+
+	mac=$(echo -n $mac | tr -d \")
+	[ ${#mac} -gt 17 ] && return
+	[ -n "${mac//[a-fA-F0-9\.: -]/}" ] && return
+
+	for octet in ${mac//[\.:-]/ }; do
+		case "${#octet}" in
+		1)
+			octet="0${octet}"
+			;;
+		2)
+			;;
+		4)
+			octet="${octet:0:2} ${octet:2:2}"
+			;;
+		12)
+			octet="${octet:0:2} ${octet:2:2} ${octet:4:2} ${octet:6:2} ${octet:8:2} ${octet:10:2}"
+			;;
+		*)
+			return
+			;;
+		esac
+		canon=${canon}${canon:+ }${octet}
+	done
+
+	[ ${#canon} -ne 17 ] && return
+
+	printf "%02x:%02x:%02x:%02x:%02x:%02x" 0x${canon// / 0x} 2>/dev/null
+}
+
+dt_is_enabled() {
+	grep -q okay "/proc/device-tree/$1/status"
+}
diff --git a/package/base-files/files/lib/functions/uci-defaults.sh b/package/base-files/files/lib/functions/uci-defaults.sh
new file mode 100644
index 0000000..5293ce1
--- /dev/null
+++ b/package/base-files/files/lib/functions/uci-defaults.sh
@@ -0,0 +1,791 @@
+. /lib/functions.sh
+. /usr/share/libubox/jshn.sh
+
+json_select_array() {
+	local _json_no_warning=1
+
+	json_select "$1"
+	[ $? = 0 ] && return
+
+	json_add_array "$1"
+	json_close_array
+
+	json_select "$1"
+}
+
+json_select_object() {
+	local _json_no_warning=1
+
+	json_select "$1"
+	[ $? = 0 ] && return
+
+	json_add_object "$1"
+	json_close_object
+
+	json_select "$1"
+}
+
+ucidef_set_interface() {
+	local network=$1; shift
+
+	[ -z "$network" ] && return
+
+	json_select_object network
+	json_select_object "$network"
+
+	while [ -n "$1" ]; do
+		local opt=$1; shift
+		local val=$1; shift
+
+		[ -n "$opt" -a -n "$val" ] || break
+
+		[ "$opt" = "device" -a "$val" != "${val/ //}" ] && {
+			json_select_array "ports"
+			for e in $val; do json_add_string "" "$e"; done
+			json_close_array
+		} || {
+			json_add_string "$opt" "$val"
+		}
+	done
+
+	if ! json_is_a protocol string; then
+		case "$network" in
+			lan) json_add_string protocol static ;;
+			wan) json_add_string protocol dhcp ;;
+			*) json_add_string protocol none ;;
+		esac
+	fi
+
+	json_select ..
+	json_select ..
+}
+
+ucidef_set_board_id() {
+	json_select_object model
+	json_add_string id "$1"
+	json_select ..
+}
+
+ucidef_set_model_name() {
+	json_select_object model
+	json_add_string name "$1"
+	json_select ..
+}
+
+ucidef_set_compat_version() {
+	json_select_object system
+	json_add_string compat_version "${1:-1.0}"
+	json_select ..
+}
+
+ucidef_set_interface_lan() {
+	ucidef_set_interface "lan" device "$1" protocol "${2:-static}"
+}
+
+ucidef_set_interface_wan() {
+	ucidef_set_interface "wan" device "$1" protocol "${2:-dhcp}"
+}
+
+ucidef_set_interfaces_lan_wan() {
+	local lan_if="$1"
+	local wan_if="$2"
+
+	ucidef_set_interface_lan "$lan_if"
+	ucidef_set_interface_wan "$wan_if"
+}
+
+ucidef_set_bridge_device() {
+	json_select_object bridge
+	json_add_string name "${1:-switch0}"
+	json_select ..
+}
+
+ucidef_set_bridge_mac() {
+	json_select_object bridge
+	json_add_string macaddr "${1}"
+	json_select ..
+}
+
+_ucidef_set_network_device_common() {
+	json_select_object "network_device"
+	json_select_object "${1}"
+	json_add_string "${2}" "${3}"
+	json_select ..
+	json_select ..
+}
+
+ucidef_set_network_device_mac() {
+	_ucidef_set_network_device_common $1 macaddr $2
+}
+
+ucidef_set_network_device_path() {
+	_ucidef_set_network_device_common $1 path $2
+}
+
+ucidef_set_network_device_path_port() {
+	_ucidef_set_network_device_common $1 path $2
+	_ucidef_set_network_device_common $1 port $3
+}
+
+ucidef_set_network_device_gro() {
+	_ucidef_set_network_device_common $1 gro $2
+}
+
+ucidef_set_network_device_conduit() {
+	_ucidef_set_network_device_common $1 conduit $2
+}
+
+_ucidef_add_switch_port() {
+	# inherited: $num $device $need_tag $want_untag $role $index $prev_role
+	# inherited: $n_cpu $n_ports $n_vlan $cpu0 $cpu1 $cpu2 $cpu3 $cpu4 $cpu5
+
+	n_ports=$((n_ports + 1))
+
+	json_select_array ports
+		json_add_object
+			json_add_int num "$num"
+			[ -n "$device"     ] && json_add_string  device     "$device"
+			[ -n "$need_tag"   ] && json_add_boolean need_tag   "$need_tag"
+			[ -n "$want_untag" ] && json_add_boolean want_untag "$want_untag"
+			[ -n "$role"       ] && json_add_string  role       "$role"
+			[ -n "$index"      ] && json_add_int     index      "$index"
+		json_close_object
+	json_select ..
+
+	# record pointer to cpu entry for lookup in _ucidef_finish_switch_roles()
+	[ -n "$device" ] && {
+		export "cpu$n_cpu=$n_ports"
+		n_cpu=$((n_cpu + 1))
+	}
+
+	# create/append object to role list
+	[ -n "$role" ] && {
+		json_select_array roles
+
+		if [ "$role" != "$prev_role" ]; then
+			json_add_object
+				json_add_string role "$role"
+				json_add_string ports "$num"
+			json_close_object
+
+			prev_role="$role"
+			n_vlan=$((n_vlan + 1))
+		else
+			json_select_object "$n_vlan"
+				json_get_var port ports
+				json_add_string ports "$port $num"
+			json_select ..
+		fi
+
+		json_select ..
+	}
+}
+
+_ucidef_finish_switch_roles() {
+	# inherited: $name $n_cpu $n_vlan $cpu0 $cpu1 $cpu2 $cpu3 $cpu4 $cpu5
+	local index role roles num device need_tag want_untag port ports
+
+	json_select switch
+		json_select "$name"
+			json_get_keys roles roles
+		json_select ..
+	json_select ..
+
+	for index in $roles; do
+		eval "port=\$cpu$(((index - 1) % n_cpu))"
+
+		json_select switch
+			json_select "$name"
+				json_select ports
+					json_select "$port"
+						json_get_vars num device need_tag want_untag
+					json_select ..
+				json_select ..
+
+				if [ ${need_tag:-0} -eq 1 -o ${want_untag:-0} -ne 1 ]; then
+					num="${num}t"
+					device="${device}.${index}"
+				fi
+
+				json_select roles
+					json_select "$index"
+						json_get_vars role ports
+						json_add_string ports "$ports $num"
+						json_add_string device "$device"
+					json_select ..
+				json_select ..
+			json_select ..
+		json_select ..
+
+		json_select_object network
+			local devices
+
+			json_select_object "$role"
+				# attach previous interfaces (for multi-switch devices)
+				json_get_var devices device
+				if ! list_contains devices "$device"; then
+					devices="${devices:+$devices }$device"
+				fi
+			json_select ..
+		json_select ..
+
+		ucidef_set_interface "$role" device "$devices"
+	done
+}
+
+ucidef_set_ar8xxx_switch_mib() {
+	local name="$1"
+	local type="$2"
+	local interval="$3"
+
+	json_select_object switch
+		json_select_object "$name"
+			json_add_int ar8xxx_mib_type $type
+			json_add_int ar8xxx_mib_poll_interval $interval
+		json_select ..
+	json_select ..
+}
+
+ucidef_add_switch() {
+	local name="$1"; shift
+	local port num role device index need_tag prev_role
+	local cpu0 cpu1 cpu2 cpu3 cpu4 cpu5
+	local n_cpu=0 n_vlan=0 n_ports=0
+
+	json_select_object switch
+		json_select_object "$name"
+			json_add_boolean enable 1
+			json_add_boolean reset 1
+
+			for port in "$@"; do
+				case "$port" in
+					[0-9]*@*)
+						num="${port%%@*}"
+						device="${port##*@}"
+						need_tag=0
+						want_untag=0
+						[ "${num%t}" != "$num" ] && {
+							num="${num%t}"
+							need_tag=1
+						}
+						[ "${num%u}" != "$num" ] && {
+							num="${num%u}"
+							want_untag=1
+						}
+					;;
+					[0-9]*:*:[0-9]*)
+						num="${port%%:*}"
+						index="${port##*:}"
+						role="${port#[0-9]*:}"; role="${role%:*}"
+					;;
+					[0-9]*:*)
+						num="${port%%:*}"
+						role="${port##*:}"
+					;;
+				esac
+
+				if [ -n "$num" ] && [ -n "$device$role" ]; then
+					_ucidef_add_switch_port
+				fi
+
+				unset num device role index need_tag want_untag
+			done
+		json_select ..
+	json_select ..
+
+	_ucidef_finish_switch_roles
+}
+
+ucidef_add_switch_attr() {
+	local name="$1"
+	local key="$2"
+	local val="$3"
+
+	json_select_object switch
+		json_select_object "$name"
+
+		case "$val" in
+			true|false) [ "$val" != "true" ]; json_add_boolean "$key" $? ;;
+			[0-9]) json_add_int "$key" "$val" ;;
+			*) json_add_string "$key" "$val" ;;
+		esac
+
+		json_select ..
+	json_select ..
+}
+
+ucidef_add_switch_port_attr() {
+	local name="$1"
+	local port="$2"
+	local key="$3"
+	local val="$4"
+	local ports i num
+
+	json_select_object switch
+	json_select_object "$name"
+
+	json_get_keys ports ports
+	json_select_array ports
+
+	for i in $ports; do
+		json_select "$i"
+		json_get_var num num
+
+		if [ -n "$num" ] && [ $num -eq $port ]; then
+			json_select_object attr
+
+			case "$val" in
+				true|false) [ "$val" != "true" ]; json_add_boolean "$key" $? ;;
+				[0-9]) json_add_int "$key" "$val" ;;
+				*) json_add_string "$key" "$val" ;;
+			esac
+
+			json_select ..
+		fi
+
+		json_select ..
+	done
+
+	json_select ..
+	json_select ..
+	json_select ..
+}
+
+ucidef_set_interface_macaddr() {
+	local network="$1"
+	local macaddr="$2"
+
+	ucidef_set_interface "$network" macaddr "$macaddr"
+}
+
+ucidef_set_label_macaddr() {
+	local macaddr="$1"
+
+	json_select_object system
+		json_add_string label_macaddr "$macaddr"
+	json_select ..
+}
+
+ucidef_add_atm_bridge() {
+	local vpi="$1"
+	local vci="$2"
+	local encaps="$3"
+	local payload="$4"
+	local nameprefix="$5"
+
+	json_select_object dsl
+		json_select_object atmbridge
+			json_add_int vpi "$vpi"
+			json_add_int vci "$vci"
+			json_add_string encaps "$encaps"
+			json_add_string payload "$payload"
+			json_add_string nameprefix "$nameprefix"
+		json_select ..
+	json_select ..
+}
+
+ucidef_add_adsl_modem() {
+	local annex="$1"
+	local firmware="$2"
+
+	json_select_object dsl
+		json_select_object modem
+			json_add_string type "adsl"
+			json_add_string annex "$annex"
+			json_add_string firmware "$firmware"
+		json_select ..
+	json_select ..
+}
+
+ucidef_add_vdsl_modem() {
+	local annex="$1"
+	local tone="$2"
+	local xfer_mode="$3"
+
+	json_select_object dsl
+		json_select_object modem
+			json_add_string type "vdsl"
+			json_add_string annex "$annex"
+			json_add_string tone "$tone"
+			json_add_string xfer_mode "$xfer_mode"
+		json_select ..
+	json_select ..
+}
+
+ucidef_set_led_ataport() {
+	_ucidef_set_led_trigger "$1" "$2" "$3" ata"$4"
+}
+
+_ucidef_set_led_common() {
+	local cfg="led_$1"
+	local name="$2"
+	local sysfs="$3"
+
+	json_select_object led
+
+	json_select_object "$1"
+	json_add_string name "$name"
+	json_add_string sysfs "$sysfs"
+}
+
+ucidef_set_led_default() {
+	local default="$4"
+
+	_ucidef_set_led_common "$1" "$2" "$3"
+
+	json_add_string default "$default"
+	json_select ..
+
+	json_select ..
+}
+
+ucidef_set_led_heartbeat() {
+	_ucidef_set_led_common "$1" "$2" "$3"
+
+	json_add_string trigger heartbeat
+	json_select ..
+
+	json_select ..
+}
+
+ucidef_set_led_gpio() {
+	local gpio="$4"
+	local inverted="$5"
+
+	_ucidef_set_led_common "$1" "$2" "$3"
+
+	json_add_string trigger "$trigger"
+	json_add_string type gpio
+	json_add_int gpio "$gpio"
+	json_add_boolean inverted "$inverted"
+	json_select ..
+
+	json_select ..
+}
+
+ucidef_set_led_ide() {
+	_ucidef_set_led_trigger "$1" "$2" "$3" disk-activity
+}
+
+ucidef_set_led_netdev() {
+	local dev="$4"
+	local mode="${5:-link tx rx}"
+
+	_ucidef_set_led_common "$1" "$2" "$3"
+
+	json_add_string type netdev
+	json_add_string device "$dev"
+	json_add_string mode "$mode"
+	json_select ..
+
+	json_select ..
+}
+
+ucidef_set_led_oneshot() {
+	_ucidef_set_led_timer $1 $2 $3 "oneshot" $4 $5
+}
+
+ucidef_set_led_portstate() {
+	local port_state="$4"
+
+	_ucidef_set_led_common "$1" "$2" "$3"
+
+	json_add_string trigger port_state
+	json_add_string type portstate
+	json_add_string port_state "$port_state"
+	json_select ..
+
+	json_select ..
+}
+
+ucidef_set_led_rssi() {
+	local iface="$4"
+	local minq="$5"
+	local maxq="$6"
+	local offset="${7:-0}"
+	local factor="${8:-1}"
+
+	_ucidef_set_led_common "$1" "$2" "$3"
+
+	json_add_string type rssi
+	json_add_string name "$name"
+	json_add_string iface "$iface"
+	json_add_string minq "$minq"
+	json_add_string maxq "$maxq"
+	json_add_string offset "$offset"
+	json_add_string factor "$factor"
+	json_select ..
+
+	json_select ..
+}
+
+ucidef_set_led_switch() {
+	local trigger_name="$4"
+	local port_mask="$5"
+	local speed_mask="$6"
+	local mode="$7"
+
+	_ucidef_set_led_common "$1" "$2" "$3"
+
+	json_add_string trigger "$trigger_name"
+	json_add_string type switch
+	json_add_string mode "$mode"
+	json_add_string port_mask "$port_mask"
+	json_add_string speed_mask "$speed_mask"
+	json_select ..
+
+	json_select ..
+}
+
+_ucidef_set_led_timer() {
+	local trigger_name="$4"
+	local delayon="$5"
+	local delayoff="$6"
+
+	_ucidef_set_led_common "$1" "$2" "$3"
+
+	json_add_string type "$trigger_name"
+	json_add_string trigger "$trigger_name"
+	json_add_int delayon "$delayon"
+	json_add_int delayoff "$delayoff"
+	json_select ..
+
+	json_select ..
+}
+
+ucidef_set_led_timer() {
+	_ucidef_set_led_timer $1 $2 $3 "timer" $4 $5
+}
+
+_ucidef_set_led_trigger() {
+	local trigger_name="$4"
+
+	_ucidef_set_led_common "$1" "$2" "$3"
+
+	json_add_string trigger "$trigger_name"
+	json_select ..
+
+	json_select ..
+}
+
+ucidef_set_led_usbdev() {
+	local dev="$4"
+
+	_ucidef_set_led_common "$1" "$2" "$3"
+
+	json_add_string type usb
+	json_add_string device "$dev"
+	json_select ..
+
+	json_select ..
+}
+
+ucidef_set_led_usbhost() {
+	_ucidef_set_led_trigger "$1" "$2" "$3" usb-host
+}
+
+ucidef_set_led_usbport() {
+	local obj="$1"
+	local name="$2"
+	local sysfs="$3"
+	shift
+	shift
+	shift
+
+	_ucidef_set_led_common "$obj" "$name" "$sysfs"
+
+	json_add_string type usbport
+	json_select_array ports
+		for port in "$@"; do
+			json_add_string port "$port"
+		done
+	json_select ..
+	json_select ..
+
+	json_select ..
+}
+
+ucidef_set_led_wlan() {
+	_ucidef_set_led_trigger "$1" "$2" "$3" "$4"
+}
+
+ucidef_set_rssimon() {
+	local dev="$1"
+	local refresh="$2"
+	local threshold="$3"
+
+	json_select_object rssimon
+
+	json_select_object "$dev"
+	[ -n "$refresh" ] && json_add_int refresh "$refresh"
+	[ -n "$threshold" ] && json_add_int threshold "$threshold"
+	json_select ..
+
+	json_select ..
+}
+
+ucidef_add_gpio_switch() {
+	local cfg="$1"
+	local name="$2"
+	local pin="$3"
+	local default="${4:-0}"
+
+	json_select_object gpioswitch
+		json_select_object "$cfg"
+			json_add_string name "$name"
+			json_add_string pin "$pin"
+			json_add_int default "$default"
+		json_select ..
+	json_select ..
+}
+
+ucidef_set_hostname() {
+	local hostname="$1"
+
+	json_select_object system
+		json_add_string hostname "$hostname"
+	json_select ..
+}
+
+ucidef_set_timezone() {
+	local timezone="$1"
+	json_select_object system
+		json_add_string timezone "$timezone"
+	json_select ..
+}
+
+ucidef_set_wireless() {
+	local band="$1"
+	local ssid="$2"
+	local encryption="$3"
+	local key="$4"
+
+	case "$band" in
+	all|2g|5g|6g) ;;
+	*) return;;
+	esac
+	[ -z "$ssid" ] && return
+
+	json_select_object wlan
+		json_select_object defaults
+			json_select_object ssids
+				json_select_object "$band"
+					json_add_string ssid "$ssid"
+					[ -n "$encryption" ] && json_add_string encryption "$encryption"
+					[ -n "$key" ] && json_add_string key "$key"
+				json_select ..
+			json_select ..
+		json_select ..
+	json_select ..
+}
+
+ucidef_set_country() {
+	local country="$1"
+
+	json_select_object wlan
+		json_select_object defaults
+			json_add_string country "$country"
+		json_select ..
+	json_select ..
+}
+
+ucidef_set_wireless_mac_count() {
+	local band="$1"
+	local mac_count="$2"
+
+	case "$band" in
+	2g|5g|6g) ;;
+	*) return;;
+	esac
+	[ -z "$mac_count" ] && return
+
+	json_select_object wlan
+		json_select_object defaults
+			json_select_object ssids
+				json_select_object "$band"
+					json_add_string mac_count "$mac_count"
+				json_select ..
+			json_select ..
+		json_select ..
+	json_select ..
+}
+
+ucidef_set_root_password_plain() {
+	local passwd="$1"
+	json_select_object credentials
+		json_add_string root_password_plain "$passwd"
+	json_select ..
+}
+
+ucidef_set_root_password_hash() {
+	local passwd="$1"
+	json_select_object credentials
+		json_add_string root_password_hash "$passwd"
+	json_select ..
+}
+
+ucidef_set_ssh_authorized_key() {
+	local ssh_key="$1"
+	json_select_object credentials
+		json_select_array ssh_authorized_keys
+			json_add_string "" "$ssh_key"
+		json_select ..
+	json_select ..
+}
+
+ucidef_set_ntpserver() {
+	local server
+
+	json_select_object system
+		json_select_array ntpserver
+			for server in "$@"; do
+				json_add_string "" "$server"
+			done
+		json_select ..
+	json_select ..
+}
+
+ucidef_set_poe() {
+	json_select_object poe
+		json_add_string "budget" "$1"
+		json_select_array ports
+			for port in $2; do
+				json_add_string "" "$port"
+			done
+		json_select ..
+	json_select ..
+}
+
+ucidef_add_wlan() {
+	local path="$1"; shift
+
+	ucidef_wlan_idx=${ucidef_wlan_idx:-0}
+
+	json_select_object wlan
+	json_select_object "wl$ucidef_wlan_idx"
+	json_add_string path "$path"
+	json_add_fields "$@"
+	json_select ..
+	json_select ..
+
+	ucidef_wlan_idx="$((ucidef_wlan_idx + 1))"
+}
+
+board_config_update() {
+	json_init
+	[ -f ${CFG} ] && json_load "$(cat ${CFG})"
+
+	# auto-initialize model id and name if applicable
+	if ! json_is_a model object; then
+		json_select_object model
+			[ -f "/tmp/sysinfo/board_name" ] && \
+				json_add_string id "$(cat /tmp/sysinfo/board_name)"
+			[ -f "/tmp/sysinfo/model" ] && \
+				json_add_string name "$(cat /tmp/sysinfo/model)"
+		json_select ..
+	fi
+}
+
+board_config_flush() {
+	json_dump -i -o ${CFG}
+}
diff --git a/package/base-files/files/lib/preinit/02_default_set_state b/package/base-files/files/lib/preinit/02_default_set_state
new file mode 100644
index 0000000..28d5f1d
--- /dev/null
+++ b/package/base-files/files/lib/preinit/02_default_set_state
@@ -0,0 +1,5 @@
+define_default_set_state() {
+	. /etc/diag.sh
+}
+
+boot_hook_add preinit_main define_default_set_state
diff --git a/package/base-files/files/lib/preinit/02_sysinfo b/package/base-files/files/lib/preinit/02_sysinfo
new file mode 100644
index 0000000..65b5096
--- /dev/null
+++ b/package/base-files/files/lib/preinit/02_sysinfo
@@ -0,0 +1,10 @@
+do_sysinfo_generic() {
+	[ -d /proc/device-tree ] || return
+	mkdir -p /tmp/sysinfo
+	[ -e /tmp/sysinfo/board_name ] || \
+		echo "$(strings /proc/device-tree/compatible | head -1)" > /tmp/sysinfo/board_name
+	[ ! -e /tmp/sysinfo/model -a -e /proc/device-tree/model ] && \
+		echo "$(cat /proc/device-tree/model)" > /tmp/sysinfo/model
+}
+
+boot_hook_add preinit_main do_sysinfo_generic
diff --git a/package/base-files/files/lib/preinit/10_indicate_failsafe b/package/base-files/files/lib/preinit/10_indicate_failsafe
new file mode 100644
index 0000000..8c950bf
--- /dev/null
+++ b/package/base-files/files/lib/preinit/10_indicate_failsafe
@@ -0,0 +1,22 @@
+# Copyright (C) 2006 OpenWrt.org
+# Copyright (C) 2010 Vertical Communications
+
+# commands for emitting messages to network in failsafe mode
+
+indicate_failsafe_led () {
+	set_state failsafe
+}
+
+indicate_failsafe() {
+	[ "$pi_preinit_no_failsafe" = "y" ] && return
+	local consoles="$(cat /sys/class/tty/console/active)"
+	[ -n "$consoles" ] || consoles=console
+	for console in $consoles; do
+		[ -c "/dev/$console" ] && echo "- failsafe -" >"/dev/$console"
+	done
+	preinit_net_echo "Entering Failsafe!\n"
+	indicate_failsafe_led
+	echo OpenWrt-failsafe > /proc/sys/kernel/hostname
+}
+
+boot_hook_add failsafe indicate_failsafe
diff --git a/package/base-files/files/lib/preinit/10_indicate_preinit b/package/base-files/files/lib/preinit/10_indicate_preinit
new file mode 100644
index 0000000..12f8fc2
--- /dev/null
+++ b/package/base-files/files/lib/preinit/10_indicate_preinit
@@ -0,0 +1,223 @@
+# Copyright (C) 2006 OpenWrt.org
+# Copyright (C) 2010 Vertical Communications
+
+preinit_ip_config() {
+	local netdev vid
+
+	netdev=${1%\.*}
+	vid=${1#*\.}
+
+	if [ "$vid" = "$netdev" ]; then
+		vid=
+	fi
+
+	grep -q "$netdev" /proc/net/dev || return
+
+	if [ -n "$vid" ]; then
+		ip link add link $netdev name $1 type vlan id $vid
+	fi
+
+	ip link set dev $netdev up
+	if [ -n "$vid" ]; then
+		ip link set dev $1 up
+	fi
+	ip -4 address add $pi_ip/$pi_netmask broadcast $pi_broadcast dev $1
+}
+
+preinit_config_switch() {
+	local role roles ports device enable reset
+
+	local name=$1
+	local lan_if=$2
+
+	json_select switch
+	json_select $name
+
+	json_get_vars enable reset
+
+	if [ "$reset" -eq "1" ]; then
+		swconfig dev $name set reset
+	fi
+	swconfig dev $name set enable_vlan $enable
+
+	if json_is_a roles array; then
+		json_get_keys roles roles
+		json_select roles
+
+		for role in $roles; do
+			json_select "$role"
+			json_get_vars ports device
+			json_select ..
+
+			if [ "$device" = "$lan_if" ]; then
+				swconfig dev $name vlan $role set ports "$ports"
+			fi
+		done
+
+		json_select ..
+	fi
+
+	swconfig dev $name set apply
+
+	json_select ..
+	json_select ..
+}
+
+preinit_config_port() {
+	local original
+	local dev_port
+
+	local netdev="$1"
+	local path="$2"
+	local port="$3"
+
+	[ -d "/sys/devices/$path/net" ] || return
+
+	if [ -z "$port" ]; then
+		original="$(ls "/sys/devices/$path/net" | head -1)"
+	else
+		for device in /sys/devices/$path/net/*; do
+			dev_port="$(cat "$device/dev_port")"
+			if [ "$dev_port" = "$port" ]; then
+				original="${device##*/}"
+				break
+			fi
+		done
+
+		[ -z "$original" ] && return
+	fi
+
+	[ "$netdev" = "$original" ] && return
+
+	ip link set "$original" name "$netdev"
+}
+
+preinit_config_board() {
+	/bin/board_detect /tmp/board.json
+
+	[ -f "/tmp/board.json" ] || return
+
+	. /usr/share/libubox/jshn.sh
+
+	json_init
+	json_load "$(cat /tmp/board.json)"
+
+	# Find the current highest eth*
+	max_eth=$(grep -o '^ *eth[0-9]*:' /proc/net/dev | tr -dc '[0-9]\n' | sort -n | tail -1)
+	# Find and move netdevs using eth*s we are configuring
+	json_get_keys keys "network_device"
+	for netdev in $keys; do
+		json_select "network_device"
+			json_select "$netdev"
+				json_get_vars path path
+				if [ -n "$path" -a -h "/sys/class/net/$netdev" ]; then
+					ip link set "$netdev" down
+					ip link set "$netdev" name eth$((++max_eth))
+				fi
+			json_select ..
+		json_select ..
+	done
+
+	# Move interfaces by path to their netdev name
+	json_get_keys keys "network_device"
+	for netdev in $keys; do
+		json_select "network_device"
+			json_select "$netdev"
+				json_get_vars path path
+				json_get_vars port port
+				[ -n "$path" ] && preinit_config_port "$netdev" "$path" "$port"
+			json_select ..
+		json_select ..
+	done
+
+	json_select network
+		json_select "lan"
+			json_get_vars device
+			json_get_values ports ports
+		json_select ..
+	json_select ..
+
+	[ -n "$device" -o -n "$ports" ] || return
+
+	# swconfig uses $device and DSA uses ports
+	[ -z "$ports" ] && {
+		ports="$device"
+	}
+
+	# only use the first one
+	ifname=${ports%% *}
+
+	if [ -x /sbin/swconfig ]; then
+		# configure the switch, if present
+
+		json_get_keys keys switch
+		for key in $keys; do
+			preinit_config_switch $key $ifname
+		done
+	else
+		# trim any vlan ids
+		ifname=${ifname%\.*}
+		# trim any vlan modifiers like :t
+		ifname=${ifname%\:*}
+	fi
+
+	pi_ifname=$ifname
+
+	preinit_ip_config $pi_ifname
+}
+
+preinit_ip() {
+	[ "$pi_preinit_no_failsafe" = "y" ] && return
+
+	# if the preinit interface isn't specified and ifname is set in
+	# preinit.arch use that interface
+	if [ -z "$pi_ifname" ]; then
+		pi_ifname=$ifname
+	fi
+
+	if [ -n "$pi_ifname" ]; then
+		preinit_ip_config $pi_ifname
+	elif [ -d "/etc/board.d/" ]; then
+		preinit_config_board
+	fi
+
+	preinit_net_echo "Doing OpenWrt Preinit\n"
+}
+
+preinit_ip_deconfig() {
+	[ -n "$pi_ifname" ] && grep -q "$pi_ifname" /proc/net/dev && {
+		local netdev vid
+
+		netdev=${pi_ifname%\.*}
+		vid=${pi_ifname#*\.}
+
+		if [ "$vid" = "$netdev" ]; then
+			vid=
+		fi
+
+		ip -4 address flush dev $pi_ifname
+		ip link set dev $netdev down
+
+		if [ -n "$vid" ]; then
+			ip link delete $pi_ifname
+		fi
+	}
+}
+
+preinit_net_echo() {
+	[ -n "$pi_ifname" ] && grep -q "$pi_ifname" /proc/net/dev && {
+		{
+			[ "$pi_preinit_net_messages" = "y" ] || {
+				[ "$pi_failsafe_net_message" = "true" ] &&
+					[ "$pi_preinit_no_failsafe_netmsg" != "y" ]
+			}
+		} && netmsg $pi_broadcast "$1"
+	}
+}
+
+pi_indicate_preinit() {
+	set_state preinit
+}
+
+boot_hook_add preinit_main preinit_ip
+boot_hook_add preinit_main pi_indicate_preinit
diff --git a/package/base-files/files/lib/preinit/30_failsafe_wait b/package/base-files/files/lib/preinit/30_failsafe_wait
new file mode 100644
index 0000000..d4ab122
--- /dev/null
+++ b/package/base-files/files/lib/preinit/30_failsafe_wait
@@ -0,0 +1,106 @@
+# Copyright (C) 2006-2010 OpenWrt.org
+# Copyright (C) 2010 Vertical Communications
+
+fs_wait_for_key () {
+	local timeout=$3
+	local timer
+	local do_keypress
+	local keypress_true="$(mktemp)"
+	local keypress_wait="$(mktemp)"
+	local keypress_sec="$(mktemp)"
+	if [ -z "$keypress_wait" ]; then
+		keypress_wait=/tmp/.keypress_wait
+		touch $keypress_wait
+	fi
+	if [ -z "$keypress_true" ]; then
+		keypress_true=/tmp/.keypress_true
+		touch $keypress_true
+	fi
+	if [ -z "$keypress_sec" ]; then
+		keypress_sec=/tmp/.keypress_sec
+		touch $keypress_sec
+	fi
+
+	trap "echo 'true' >$keypress_true; lock -u $keypress_wait ; rm -f $keypress_wait" INT
+	trap "echo 'true' >$keypress_true; lock -u $keypress_wait ; rm -f $keypress_wait" USR1
+
+	[ -n "$timeout" ] || timeout=1
+	[ $timeout -ge 1 ] || timeout=1
+	timer=$timeout
+	lock $keypress_wait
+	{
+		while [ $timer -gt 0 ]; do
+			pi_failsafe_net_message=true \
+				preinit_net_echo "Please press button now to enter failsafe"
+			echo "$timer" >$keypress_sec
+			timer=$(($timer - 1))
+			sleep 1
+		done
+		lock -u $keypress_wait
+		rm -f $keypress_wait
+	} &
+
+	local consoles="$(cat /sys/class/tty/console/active)"
+	[ -n "$consoles" ] || consoles=console
+	for console in $consoles; do
+		[ -c "/dev/$console" ] || continue
+		[ "$pi_preinit_no_failsafe" != "y" ] && echo "Press the [$1] key and hit [enter] $2" > "/dev/$console"
+		echo "Press the [1], [2], [3] or [4] key and hit [enter] to select the debug level" > "/dev/$console"
+		{
+			while [ -r $keypress_wait ]; do
+				timer="$(cat $keypress_sec)"
+
+				[ -n "$timer" ] || timer=1
+				timer="${timer%%\ *}"
+#				[ $timer -ge 1 ] || timer=1
+				timer=0
+				do_keypress=""
+				{
+					read -t "$timer" do_keypress < "/dev/$console"
+					case "$do_keypress" in
+					$1)
+						echo "true" >$keypress_true
+						;;
+					1 | 2 | 3 | 4)
+						echo "$do_keypress" >/tmp/debug_level
+						;;
+					*)
+						continue;
+						;;
+					esac
+					lock -u $keypress_wait
+					rm -f $keypress_wait
+				}
+			done
+		} &
+	done
+	lock -w $keypress_wait
+
+	keypressed=1
+	[ "$(cat $keypress_true)" = "true" ] && keypressed=0
+
+	trap - INT
+	trap - USR1
+
+	rm -f $keypress_true
+	rm -f $keypress_wait
+	rm -f $keypress_sec
+
+	return $keypressed
+}
+
+failsafe_wait() {
+	FAILSAFE=
+	[ "$pi_preinit_no_failsafe" = "y" ] && {
+		fs_wait_for_key "" "" $fs_failsafe_wait_timeout
+		return
+	}
+	grep -q 'failsafe=' /proc/cmdline && FAILSAFE=true && export FAILSAFE
+	if [ "$FAILSAFE" != "true" ]; then
+		fs_wait_for_key f 'to enter failsafe mode' $fs_failsafe_wait_timeout && FAILSAFE=true
+		[ -f "/tmp/failsafe_button" ] && FAILSAFE=true && echo "- failsafe button "$(cat /tmp/failsafe_button)" was pressed -"
+		[ "$FAILSAFE" = "true" ] && export FAILSAFE && touch /tmp/failsafe
+	fi
+}
+
+boot_hook_add preinit_main failsafe_wait
diff --git a/package/base-files/files/lib/preinit/40_run_failsafe_hook b/package/base-files/files/lib/preinit/40_run_failsafe_hook
new file mode 100644
index 0000000..e3f769a
--- /dev/null
+++ b/package/base-files/files/lib/preinit/40_run_failsafe_hook
@@ -0,0 +1,16 @@
+# Copyright (C) 2006-2010 OpenWrt.org
+# Copyright (C) 2010 Vertical Communications
+
+run_failsafe_hook() {
+    [ "$pi_preinit_no_failsafe" = "y" ] && return
+    if [ "$FAILSAFE" = "true" ]; then
+	lock /tmp/.failsafe
+	boot_run_hook failsafe
+	while [ ! -e /tmp/sysupgrade ]; do
+	    lock -w /tmp/.failsafe
+	done
+	exit
+    fi
+}
+
+boot_hook_add preinit_main run_failsafe_hook
diff --git a/package/base-files/files/lib/preinit/50_indicate_regular_preinit b/package/base-files/files/lib/preinit/50_indicate_regular_preinit
new file mode 100644
index 0000000..f4afcdd
--- /dev/null
+++ b/package/base-files/files/lib/preinit/50_indicate_regular_preinit
@@ -0,0 +1,9 @@
+# Copyright (C) 2006 OpenWrt.org
+# Copyright (C) 2010 Vertical Communications
+
+indicate_regular_preinit() {
+	preinit_net_echo "Continuing with Regular Preinit\n"
+	set_state preinit_regular
+}
+
+boot_hook_add preinit_main indicate_regular_preinit
diff --git a/package/base-files/files/lib/preinit/70_initramfs_test b/package/base-files/files/lib/preinit/70_initramfs_test
new file mode 100644
index 0000000..c5aae98
--- /dev/null
+++ b/package/base-files/files/lib/preinit/70_initramfs_test
@@ -0,0 +1,12 @@
+# Copyright (C) 2006 OpenWrt.org
+# Copyright (C) 2010 Vertical Communications
+
+initramfs_test() {
+	if [ -n "$INITRAMFS" ]; then
+		boot_run_hook initramfs
+		preinit_ip_deconfig
+		break
+	fi
+}
+
+boot_hook_add preinit_main initramfs_test
diff --git a/package/base-files/files/lib/preinit/80_mount_root b/package/base-files/files/lib/preinit/80_mount_root
new file mode 100644
index 0000000..dd79b27
--- /dev/null
+++ b/package/base-files/files/lib/preinit/80_mount_root
@@ -0,0 +1,54 @@
+# Copyright (C) 2006 OpenWrt.org
+# Copyright (C) 2010 Vertical Communications
+
+missing_lines() {
+	local file1 file2 line
+	file1="$1"
+	file2="$2"
+	oIFS="$IFS"
+	IFS=":"
+	while read line; do
+		set -- $line
+		grep -q "^$1:" "$file2" || echo "$line"
+	done < "$file1"
+	IFS="$oIFS"
+}
+
+# Rootfs mount options can be passed by declaring in the kernel
+# cmdline as much options as needed prefixed with "rootfs_mount_options."
+#
+# Example:
+# rootfs_mount_options.compress_algorithm=zstd rootfs_mount_options.noinline_data
+#
+compose_rootfs_mount_options() {
+	local mount_options
+	local cmdlinevar
+
+	for cmdlinevar in $(cat /proc/cmdline); do
+		if [ "$cmdlinevar" != "${cmdlinevar#rootfs_mount_options\.}" ]; then
+			append mount_options "${cmdlinevar#rootfs_mount_options\.}"
+		fi
+	done
+
+	echo $mount_options
+}
+
+do_mount_root() {
+	#mount_root start "$(compose_rootfs_mount_options)"
+	boot_run_hook preinit_mount_root
+	[ -f /sysupgrade.tgz -o -f /tmp/sysupgrade.tar ] && {
+		echo "- config restore -"
+		cp /etc/passwd /etc/group /etc/shadow /tmp
+		cd /
+		[ -f /sysupgrade.tgz ] && tar xzf /sysupgrade.tgz
+		[ -f /tmp/sysupgrade.tar ] && tar xf /tmp/sysupgrade.tar
+		missing_lines /tmp/passwd /etc/passwd >> /etc/passwd
+		missing_lines /tmp/group /etc/group >> /etc/group
+		missing_lines /tmp/shadow /etc/shadow >> /etc/shadow
+		rm /tmp/passwd /tmp/group /tmp/shadow
+		# Prevent configuration corruption on a power loss
+		sync
+	}
+}
+
+[ "$INITRAMFS" = "1" ] || boot_hook_add preinit_main do_mount_root
diff --git a/package/base-files/files/lib/preinit/99_10_failsafe_login b/package/base-files/files/lib/preinit/99_10_failsafe_login
new file mode 100644
index 0000000..f72a35e
--- /dev/null
+++ b/package/base-files/files/lib/preinit/99_10_failsafe_login
@@ -0,0 +1,23 @@
+# Copyright (C) 2006-2015 OpenWrt.org
+# Copyright (C) 2010 Vertical Communications
+
+failsafe_shell() {
+	local consoles="$(cat /sys/class/tty/console/active)"
+	[ -n "$consoles" ] || consoles=console
+	for console in $consoles; do
+		case "$console" in
+			console|tty[0-9]*)
+				term=${TERM:-linux}
+				;;
+			*)
+				term=vt102
+				;;
+		esac
+		# Running asynchronously via the shell's & would ignore SIGINT,
+		# breaking ^C. Use start-stop-daemon instead.
+		[ -c "/dev/$console" ] && start-stop-daemon -Sb -p /dev/null -- env -i ash -c "while true; do setsid -c env -i USER=root LOGNAME=root SHELL=/bin/ash TERM="$term" ash --login <\"/dev/$console\" >\"/dev/$console\" 2>\"/dev/$console\"; sleep 1; done"
+	done
+
+}
+
+boot_hook_add failsafe failsafe_shell
diff --git a/package/base-files/files/lib/preinit/99_10_run_init b/package/base-files/files/lib/preinit/99_10_run_init
new file mode 100644
index 0000000..ebf77b0
--- /dev/null
+++ b/package/base-files/files/lib/preinit/99_10_run_init
@@ -0,0 +1,8 @@
+# Copyright (C) 2006 OpenWrt.org
+# Copyright (C) 2010 Vertical Communications
+
+run_init() {
+	preinit_ip_deconfig
+}
+
+boot_hook_add preinit_main run_init
diff --git a/package/base-files/files/lib/upgrade/common.sh b/package/base-files/files/lib/upgrade/common.sh
new file mode 100644
index 0000000..af1182c
--- /dev/null
+++ b/package/base-files/files/lib/upgrade/common.sh
@@ -0,0 +1,317 @@
+RAM_ROOT=/tmp/root
+
+export BACKUP_FILE=sysupgrade.tgz	# file extracted by preinit
+
+[ -x /usr/bin/ldd ] || ldd() { LD_TRACE_LOADED_OBJECTS=1 $*; }
+libs() { ldd $* 2>/dev/null | sed -E 's/(.* => )?(.*) .*/\2/'; }
+
+install_file() { # <file> [ <file> ... ]
+	local target dest dir
+	for file in "$@"; do
+		if [ -L "$file" ]; then
+			target="$(readlink -f "$file")"
+			dest="$RAM_ROOT/$file"
+			[ ! -f "$dest" ] && {
+				dir="$(dirname "$dest")"
+				mkdir -p "$dir"
+				ln -s "$target" "$dest"
+			}
+			file="$target"
+		fi
+		dest="$RAM_ROOT/$file"
+		[ -f "$file" -a ! -f "$dest" ] && {
+			dir="$(dirname "$dest")"
+			mkdir -p "$dir"
+			cp "$file" "$dest"
+		}
+	done
+}
+
+install_bin() {
+	local src files
+	src=$1
+	files=$1
+	[ -x "$src" ] && files="$src $(libs $src)"
+	install_file $files
+}
+
+run_hooks() {
+	local arg="$1"; shift
+	for func in "$@"; do
+		eval "$func $arg"
+	done
+}
+
+ask_bool() {
+	local default="$1"; shift;
+	local answer="$default"
+
+	[ "$INTERACTIVE" -eq 1 ] && {
+		case "$default" in
+			0) echo -n "$* (y/N): ";;
+			*) echo -n "$* (Y/n): ";;
+		esac
+		read answer
+		case "$answer" in
+			y*) answer=1;;
+			n*) answer=0;;
+			*) answer="$default";;
+		esac
+	}
+	[ "$answer" -gt 0 ]
+}
+
+_v() {
+	[ -n "$VERBOSE" ] && [ "$VERBOSE" -ge 1 ] && echo "$*" >&2
+}
+
+v() {
+	_v "$(date) upgrade: $@"
+	logger -p info -t upgrade "$@"
+}
+
+json_string() {
+	local v="$1"
+	v="${v//\\/\\\\}"
+	v="${v//\"/\\\"}"
+	echo "\"$v\""
+}
+
+rootfs_type() {
+	/bin/mount | awk '($3 ~ /^\/$/) && ($5 !~ /rootfs/) { print $5 }'
+}
+
+get_image() { # <source> [ <command> ]
+	local from="$1"
+	local cmd="$2"
+
+	if [ -z "$cmd" ]; then
+		local magic="$(dd if="$from" bs=2 count=1 2>/dev/null | hexdump -n 2 -e '1/1 "%02x"')"
+		case "$magic" in
+			1f8b) cmd="busybox zcat";;
+			*) cmd="cat";;
+		esac
+	fi
+
+	$cmd <"$from"
+}
+
+get_image_dd() {
+	local from="$1"; shift
+
+	(
+		exec 3>&2
+		( exec 3>&2; get_image "$from" 2>&1 1>&3 | grep -v -F ' Broken pipe'     ) 2>&1 1>&3 \
+			| ( exec 3>&2; dd "$@" 2>&1 1>&3 | grep -v -E ' records (in|out)') 2>&1 1>&3
+		exec 3>&-
+	)
+}
+
+get_magic_word() {
+	(get_image "$@" | dd bs=2 count=1 | hexdump -v -n 2 -e '1/1 "%02x"') 2>/dev/null
+}
+
+get_magic_long() {
+	(get_image "$@" | dd bs=4 count=1 | hexdump -v -n 4 -e '1/1 "%02x"') 2>/dev/null
+}
+
+get_magic_gpt() {
+	(get_image "$@" | dd bs=8 count=1 skip=64) 2>/dev/null
+}
+
+get_magic_vfat() {
+	(get_image "$@" | dd bs=3 count=1 skip=18) 2>/dev/null
+}
+
+get_magic_fat32() {
+	(get_image "$@" | dd bs=1 count=5 skip=82) 2>/dev/null
+}
+
+identify_magic_long() {
+	local magic=$1
+	case "$magic" in
+		"55424923")
+			echo "ubi"
+			;;
+		"31181006")
+			echo "ubifs"
+			;;
+		"68737173")
+			echo "squashfs"
+			;;
+		"d00dfeed")
+			echo "fit"
+			;;
+		"4349"*)
+			echo "combined"
+			;;
+		"1f8b"*)
+			echo "gzip"
+			;;
+		*)
+			echo "unknown $magic"
+			;;
+	esac
+}
+
+part_magic_efi() {
+	local magic=$(get_magic_gpt "$@")
+	[ "$magic" = "EFI PART" ]
+}
+
+part_magic_fat() {
+	local magic=$(get_magic_vfat "$@")
+	local magic_fat32=$(get_magic_fat32 "$@")
+	[ "$magic" = "FAT" ] || [ "$magic_fat32" = "FAT32" ]
+}
+
+export_bootdevice() {
+	local cmdline uuid blockdev uevent line class
+	local MAJOR MINOR DEVNAME DEVTYPE
+	local rootpart="$(cmdline_get_var root)"
+
+	case "$rootpart" in
+		PARTUUID=[a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9]-[a-f0-9][a-f0-9])
+			uuid="${rootpart#PARTUUID=}"
+			uuid="${uuid%-[a-f0-9][a-f0-9]}"
+			for blockdev in $(find /dev -type b); do
+				set -- $(dd if=$blockdev bs=1 skip=440 count=4 2>/dev/null | hexdump -v -e '4/1 "%02x "')
+				if [ "$4$3$2$1" = "$uuid" ]; then
+					uevent="/sys/class/block/${blockdev##*/}/uevent"
+					break
+				fi
+			done
+		;;
+		PARTUUID=????????-????-????-????-??????????0?/PARTNROFF=1 | \
+		PARTUUID=????????-????-????-????-??????????02)
+			uuid="${rootpart#PARTUUID=}"
+			uuid="${uuid%/PARTNROFF=1}"
+			uuid="${uuid%0?}00"
+			for disk in $(find /dev -type b); do
+				set -- $(dd if=$disk bs=1 skip=568 count=16 2>/dev/null | hexdump -v -e '8/1 "%02x "" "2/1 "%02x""-"6/1 "%02x"')
+				if [ "$4$3$2$1-$6$5-$8$7-$9" = "$uuid" ]; then
+					uevent="/sys/class/block/${disk##*/}/uevent"
+					break
+				fi
+			done
+		;;
+		/dev/*)
+			uevent="/sys/class/block/${rootpart##*/}/../uevent"
+		;;
+		0x[a-f0-9][a-f0-9][a-f0-9] | 0x[a-f0-9][a-f0-9][a-f0-9][a-f0-9] | \
+		[a-f0-9][a-f0-9][a-f0-9] | [a-f0-9][a-f0-9][a-f0-9][a-f0-9])
+			rootpart=0x${rootpart#0x}
+			for class in /sys/class/block/*; do
+				while read line; do
+					export -n "$line"
+				done < "$class/uevent"
+				if [ $((rootpart/256)) = $MAJOR -a $((rootpart%256)) = $MINOR ]; then
+					uevent="$class/../uevent"
+				fi
+			done
+		;;
+	esac
+
+	if [ -e "$uevent" ]; then
+		while read line; do
+			export -n "$line"
+		done < "$uevent"
+		export BOOTDEV_MAJOR=$MAJOR
+		export BOOTDEV_MINOR=$MINOR
+		return 0
+	fi
+
+	return 1
+}
+
+export_partdevice() {
+	local var="$1" offset="$2"
+	local uevent line MAJOR MINOR DEVNAME DEVTYPE
+
+	for uevent in /sys/class/block/*/uevent; do
+		while read line; do
+			export -n "$line"
+		done < "$uevent"
+		if [ "$BOOTDEV_MAJOR" = "$MAJOR" -a $(($BOOTDEV_MINOR + $offset)) = "$MINOR" -a -b "/dev/$DEVNAME" ]; then
+			export "$var=$DEVNAME"
+			return 0
+		fi
+	done
+
+	return 1
+}
+
+hex_le32_to_cpu() {
+	[ "$(echo 01 | hexdump -v -n 2 -e '/2 "%x"')" = "3031" ] && {
+		echo "${1:0:2}${1:8:2}${1:6:2}${1:4:2}${1:2:2}"
+		return
+	}
+	echo "$@"
+}
+
+get_partitions() { # <device> <filename>
+	local disk="$1"
+	local filename="$2"
+
+	if [ -b "$disk" -o -f "$disk" ]; then
+		v "Reading partition table from $filename..."
+
+		local magic=$(dd if="$disk" bs=2 count=1 skip=255 2>/dev/null)
+		if [ "$magic" != $'\x55\xAA' ]; then
+			v "Invalid partition table on $disk"
+			exit
+		fi
+
+		rm -f "/tmp/partmap.$filename"
+
+		local part
+		part_magic_efi "$disk" && {
+			#export_partdevice will fail when partition number is greater than 15, as
+			#the partition major device number is not equal to the disk major device number
+			for part in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15; do
+				set -- $(hexdump -v -n 48 -s "$((0x380 + $part * 0x80))" -e '4/4 "%08x"" "4/4 "%08x"" "4/4 "0x%08X "' "$disk")
+
+				local type="$1"
+				local lba="$(( $(hex_le32_to_cpu $4) * 0x100000000 + $(hex_le32_to_cpu $3) ))"
+				local end="$(( $(hex_le32_to_cpu $6) * 0x100000000 + $(hex_le32_to_cpu $5) ))"
+				local num="$(( $end - $lba + 1 ))"
+
+				[ "$type" = "00000000000000000000000000000000" ] && continue
+
+				printf "%2d %5d %7d\n" $part $lba $num >> "/tmp/partmap.$filename"
+			done
+		} || {
+			for part in 1 2 3 4; do
+				set -- $(hexdump -v -n 12 -s "$((0x1B2 + $part * 16))" -e '3/4 "0x%08X "' "$disk")
+
+				local type="$(( $(hex_le32_to_cpu $1) % 256))"
+				local lba="$(( $(hex_le32_to_cpu $2) ))"
+				local num="$(( $(hex_le32_to_cpu $3) ))"
+
+				[ $type -gt 0 ] || continue
+
+				printf "%2d %5d %7d\n" $part $lba $num >> "/tmp/partmap.$filename"
+			done
+		}
+	fi
+}
+
+indicate_upgrade() {
+	. /etc/diag.sh
+	set_state upgrade
+}
+
+# Flash firmware to MTD partition
+#
+# $(1): path to image
+# $(2): (optional) pipe command to extract firmware, e.g. dd bs=n skip=m
+default_do_upgrade() {
+	sync
+	echo 3 > /proc/sys/vm/drop_caches
+	if [ -n "$UPGRADE_BACKUP" ]; then
+		get_image "$1" "$2" | mtd $MTD_ARGS $MTD_CONFIG_ARGS -j "$UPGRADE_BACKUP" write - "${PART_NAME:-image}"
+	else
+		get_image "$1" "$2" | mtd $MTD_ARGS write - "${PART_NAME:-image}"
+	fi
+	[ $? -ne 0 ] && exit 1
+}
diff --git a/package/base-files/files/lib/upgrade/do_stage2 b/package/base-files/files/lib/upgrade/do_stage2
new file mode 100755
index 0000000..0e32445
--- /dev/null
+++ b/package/base-files/files/lib/upgrade/do_stage2
@@ -0,0 +1,25 @@
+#!/bin/sh
+
+. /lib/functions.sh
+
+include /lib/upgrade
+
+v "Performing system upgrade..."
+if type 'platform_do_upgrade' >/dev/null 2>/dev/null; then
+	platform_do_upgrade "$IMAGE"
+else
+	default_do_upgrade "$IMAGE"
+fi
+
+if [ -n "$UPGRADE_BACKUP" ] && type 'platform_copy_config' >/dev/null 2>/dev/null; then
+	platform_copy_config
+fi
+
+v "Upgrade completed"
+sleep 1
+
+v "Rebooting system..."
+umount -a
+reboot -f
+sleep 5
+echo b 2>/dev/null >/proc/sysrq-trigger
diff --git a/package/base-files/files/lib/upgrade/emmc.sh b/package/base-files/files/lib/upgrade/emmc.sh
new file mode 100644
index 0000000..78e398d
--- /dev/null
+++ b/package/base-files/files/lib/upgrade/emmc.sh
@@ -0,0 +1,74 @@
+# Copyright (C) 2021 OpenWrt.org
+#
+
+. /lib/functions.sh
+
+emmc_upgrade_tar() {
+	local tar_file="$1"
+	[ "$CI_KERNPART" -a -z "$EMMC_KERN_DEV" ] && export EMMC_KERN_DEV="$(find_mmc_part $CI_KERNPART $CI_ROOTDEV)"
+	[ "$CI_ROOTPART" -a -z "$EMMC_ROOT_DEV" ] && export EMMC_ROOT_DEV="$(find_mmc_part $CI_ROOTPART $CI_ROOTDEV)"
+	[ "$CI_DATAPART" -a -z "$EMMC_DATA_DEV" ] && export EMMC_DATA_DEV="$(find_mmc_part $CI_DATAPART $CI_ROOTDEV)"
+	local has_kernel
+	local has_rootfs
+	local board_dir=$(tar tf "$tar_file" | grep -m 1 '^sysupgrade-.*/$')
+	board_dir=${board_dir%/}
+
+	tar tf "$tar_file" ${board_dir}/kernel 1>/dev/null 2>/dev/null && has_kernel=1
+	tar tf "$tar_file" ${board_dir}/root 1>/dev/null 2>/dev/null && has_rootfs=1
+
+	[ "$has_rootfs" = 1 -a "$EMMC_ROOT_DEV" ] && {
+		# Invalidate kernel image while rootfs is being written
+		[ "$has_kernel" = 1 -a "$EMMC_KERN_DEV" ] && {
+			dd if=/dev/zero of="$EMMC_KERN_DEV" bs=512 count=8
+			sync
+		}
+
+		export EMMC_ROOTFS_BLOCKS=$(($(tar xf "$tar_file" ${board_dir}/root -O | dd of="$EMMC_ROOT_DEV" bs=512 2>&1 | grep "records out" | cut -d' ' -f1)))
+		# Account for 64KiB ROOTDEV_OVERLAY_ALIGN in libfstools
+		EMMC_ROOTFS_BLOCKS=$(((EMMC_ROOTFS_BLOCKS + 127) & ~127))
+		sync
+	}
+
+	[ "$has_kernel" = 1 -a "$EMMC_KERN_DEV" ] &&
+		export EMMC_KERNEL_BLOCKS=$(($(tar xf "$tar_file" ${board_dir}/kernel -O | dd of="$EMMC_KERN_DEV" bs=512 2>&1 | grep "records out" | cut -d' ' -f1)))
+
+	if [ -z "$UPGRADE_BACKUP" ]; then
+		if [ "$EMMC_DATA_DEV" ]; then
+			dd if=/dev/zero of="$EMMC_DATA_DEV" bs=512 count=8
+		elif [ "$EMMC_ROOTFS_BLOCKS" ]; then
+			dd if=/dev/zero of="$EMMC_ROOT_DEV" bs=512 seek=$EMMC_ROOTFS_BLOCKS count=8
+		elif [ "$EMMC_KERNEL_BLOCKS" ]; then
+			dd if=/dev/zero of="$EMMC_KERN_DEV" bs=512 seek=$EMMC_KERNEL_BLOCKS count=8
+		fi
+	fi
+}
+
+emmc_upgrade_fit() {
+	local fit_file="$1"
+	[ "$CI_KERNPART" -a -z "$EMMC_KERN_DEV" ] && export EMMC_KERN_DEV="$(find_mmc_part $CI_KERNPART $CI_ROOTDEV)"
+
+	if [ "$EMMC_KERN_DEV" ]; then
+		export EMMC_KERNEL_BLOCKS=$(($(get_image "$fit_file" | fwtool -i /dev/null -T - | dd of="$EMMC_KERN_DEV" bs=512 2>&1 | grep "records out" | cut -d' ' -f1)))
+
+		[ -z "$UPGRADE_BACKUP" ] && dd if=/dev/zero of="$EMMC_KERN_DEV" bs=512 seek=$EMMC_KERNEL_BLOCKS count=8
+	fi
+}
+
+emmc_copy_config() {
+	if [ "$EMMC_DATA_DEV" ]; then
+		dd if="$UPGRADE_BACKUP" of="$EMMC_DATA_DEV" bs=512
+	elif [ "$EMMC_ROOTFS_BLOCKS" ]; then
+		dd if="$UPGRADE_BACKUP" of="$EMMC_ROOT_DEV" bs=512 seek=$EMMC_ROOTFS_BLOCKS
+	elif [ "$EMMC_KERNEL_BLOCKS" ]; then
+		dd if="$UPGRADE_BACKUP" of="$EMMC_KERN_DEV" bs=512 seek=$EMMC_KERNEL_BLOCKS
+	fi
+}
+
+emmc_do_upgrade() {
+	local file_type=$(identify_magic_long "$(get_magic_long "$1")")
+
+	case "$file_type" in
+		"fit")  emmc_upgrade_fit $1;;
+		*)      emmc_upgrade_tar $1;;
+	esac
+}
diff --git a/package/base-files/files/lib/upgrade/fwtool.sh b/package/base-files/files/lib/upgrade/fwtool.sh
new file mode 100644
index 0000000..8bd00a3
--- /dev/null
+++ b/package/base-files/files/lib/upgrade/fwtool.sh
@@ -0,0 +1,93 @@
+fwtool_check_signature() {
+	[ $# -gt 1 ] && return 1
+
+	[ ! -x /usr/bin/ucert ] && {
+		if [ "$REQUIRE_IMAGE_SIGNATURE" = 1 ]; then
+			return 1
+		else
+			return 0
+		fi
+	}
+
+	if ! fwtool -q -s /tmp/sysupgrade.ucert "$1"; then
+		v "Image signature not present"
+		[ "$REQUIRE_IMAGE_SIGNATURE" = 1 -a "$FORCE" != 1 ] && {
+			v "Use sysupgrade -F to override this check when downgrading or flashing to vendor firmware"
+		}
+		[ "$REQUIRE_IMAGE_SIGNATURE" = 1 ] && return 1
+		return 0
+	fi
+
+	fwtool -q -T -s /dev/null "$1" | \
+		ucert -V -m - -c "/tmp/sysupgrade.ucert" -P /etc/opkg/keys
+
+	return $?
+}
+
+fwtool_check_image() {
+	[ $# -gt 1 ] && return 1
+
+	. /usr/share/libubox/jshn.sh
+
+	if ! fwtool -q -i /tmp/sysupgrade.meta "$1"; then
+		v "Image metadata not present"
+		[ "$REQUIRE_IMAGE_METADATA" = 1 -a "$FORCE" != 1 ] && {
+			v "Use sysupgrade -F to override this check when downgrading or flashing to vendor firmware"
+		}
+		[ "$REQUIRE_IMAGE_METADATA" = 1 ] && return 1
+		return 0
+	fi
+
+	json_load "$(cat /tmp/sysupgrade.meta)" || {
+		v "Invalid image metadata"
+		return 1
+	}
+
+	device="$(cat /tmp/sysinfo/board_name)"
+	devicecompat="$(uci -q get system.@system[0].compat_version)"
+	[ -n "$devicecompat" ] || devicecompat="1.0"
+
+	json_get_var imagecompat compat_version
+	json_get_var compatmessage compat_message
+	[ -n "$imagecompat" ] || imagecompat="1.0"
+
+	# select correct supported list based on compat_version
+	# (using this ensures that compatibility check works for devices
+	#  not knowing about compat-version)
+	local supported=supported_devices
+	[ "$imagecompat" != "1.0" ] && supported=new_supported_devices
+	json_select $supported || return 1
+
+	json_get_keys dev_keys
+	for k in $dev_keys; do
+		json_get_var dev "$k"
+		if [ "$dev" = "$device" ]; then
+			# major compat version -> no sysupgrade
+			if [ "${devicecompat%.*}" != "${imagecompat%.*}" ]; then
+				v "The device is supported, but this image is incompatible for sysupgrade based on the image version ($devicecompat->$imagecompat)."
+				[ -n "$compatmessage" ] && v "$compatmessage"
+				return 1
+			fi
+
+			# minor compat version -> sysupgrade with -n required
+			if [ "${devicecompat#.*}" != "${imagecompat#.*}" ] && [ "$SAVE_CONFIG" = "1" ]; then
+				[ "$IGNORE_MINOR_COMPAT" = 1 ] && return 0
+				v "The device is supported, but the config is incompatible to the new image ($devicecompat->$imagecompat). Please upgrade without keeping config (sysupgrade -n)."
+				[ -n "$compatmessage" ] && v "$compatmessage"
+				return 1
+			fi
+
+			return 0
+		fi
+	done
+
+	v "Device $device not supported by this image"
+	local devices="Supported devices:"
+	for k in $dev_keys; do
+		json_get_var dev "$k"
+		devices="$devices $dev"
+	done
+	v "$devices"
+
+	return 1
+}
diff --git a/package/base-files/files/lib/upgrade/keep.d/base-files-essential b/package/base-files/files/lib/upgrade/keep.d/base-files-essential
new file mode 100644
index 0000000..7a7a253
--- /dev/null
+++ b/package/base-files/files/lib/upgrade/keep.d/base-files-essential
@@ -0,0 +1,11 @@
+# Essential files that will be always kept
+/etc/hosts
+/etc/inittab
+/etc/group
+/etc/passwd
+/etc/profile
+/etc/shadow
+/etc/shells
+/etc/shinit
+/etc/sysctl.conf
+/etc/rc.local
diff --git a/package/base-files/files/lib/upgrade/legacy-sdcard.sh b/package/base-files/files/lib/upgrade/legacy-sdcard.sh
new file mode 100644
index 0000000..d2ae53b
--- /dev/null
+++ b/package/base-files/files/lib/upgrade/legacy-sdcard.sh
@@ -0,0 +1,91 @@
+legacy_sdcard_check_image() {
+	local file="$1"
+	local diskdev partdev diff
+
+	export_bootdevice && export_partdevice diskdev 0 || {
+		v "Unable to determine upgrade device"
+	return 1
+	}
+
+	get_partitions "/dev/$diskdev" bootdisk
+
+	v "Extract boot sector from the image"
+	get_image_dd "$1" of=/tmp/image.bs count=1 bs=512b
+
+	get_partitions /tmp/image.bs image
+
+	#compare tables
+	diff="$(grep -F -x -v -f /tmp/partmap.bootdisk /tmp/partmap.image)"
+
+	rm -f /tmp/image.bs /tmp/partmap.bootdisk /tmp/partmap.image
+
+	if [ -n "$diff" ]; then
+		v "Partition layout has changed. Full image will be written."
+		ask_bool 0 "Abort" && exit 1
+		return 0
+	fi
+}
+
+legacy_sdcard_do_upgrade() {
+	local board=$(board_name)
+	local diskdev partdev diff
+
+	export_bootdevice && export_partdevice diskdev 0 || {
+		v "Unable to determine upgrade device"
+	return 1
+	}
+
+	sync
+
+	if [ "$UPGRADE_OPT_SAVE_PARTITIONS" = "1" ]; then
+		get_partitions "/dev/$diskdev" bootdisk
+
+		v "Extract boot sector from the image"
+		get_image_dd "$1" of=/tmp/image.bs count=1 bs=512b
+
+		get_partitions /tmp/image.bs image
+
+		#compare tables
+		diff="$(grep -F -x -v -f /tmp/partmap.bootdisk /tmp/partmap.image)"
+	else
+		diff=1
+	fi
+
+	if [ -n "$diff" ]; then
+		get_image_dd "$1" of="/dev/$diskdev" bs=4096 conv=fsync
+
+		# Separate removal and addtion is necessary; otherwise, partition 1
+		# will be missing if it overlaps with the old partition 2
+		partx -d - "/dev/$diskdev"
+		partx -a - "/dev/$diskdev"
+	else
+		v "Writing bootloader to /dev/$diskdev"
+		get_image_dd "$1" of="$diskdev" bs=512 skip=1 seek=1 count=2048 conv=fsync
+		#iterate over each partition from the image and write it to the boot disk
+		while read part start size; do
+			if export_partdevice partdev $part; then
+				v "Writing image to /dev/$partdev..."
+				get_image_dd "$1" of="/dev/$partdev" ibs="512" obs=1M skip="$start" count="$size" conv=fsync
+			else
+				v "Unable to find partition $part device, skipped."
+			fi
+		done < /tmp/partmap.image
+
+		v "Writing new UUID to /dev/$diskdev..."
+		get_image_dd "$1" of="/dev/$diskdev" bs=1 skip=440 count=4 seek=440 conv=fsync
+	fi
+
+	sleep 1
+}
+
+legacy_sdcard_copy_config() {
+	local partdev
+
+	if export_partdevice partdev 1; then
+		mkdir -p /boot
+		[ -f /boot/kernel.img ] || mount -o rw,noatime /dev/$partdev /boot
+		cp -af "$UPGRADE_BACKUP" "/boot/$BACKUP_FILE"
+		sync
+		umount /boot
+	fi
+}
diff --git a/package/base-files/files/lib/upgrade/nand.sh b/package/base-files/files/lib/upgrade/nand.sh
new file mode 100644
index 0000000..ca30255
--- /dev/null
+++ b/package/base-files/files/lib/upgrade/nand.sh
@@ -0,0 +1,499 @@
+# Copyright (C) 2014 OpenWrt.org
+#
+
+. /lib/functions.sh
+
+# 'kernel' partition or UBI volume on NAND contains the kernel
+CI_KERNPART="${CI_KERNPART:-kernel}"
+
+# 'ubi' partition on NAND contains UBI
+# There are also CI_KERN_UBIPART and CI_ROOT_UBIPART if kernel
+# and rootfs are on separated UBIs.
+CI_UBIPART="${CI_UBIPART:-ubi}"
+
+# 'rootfs' UBI volume on NAND contains the rootfs
+CI_ROOTPART="${CI_ROOTPART:-rootfs}"
+
+ubi_mknod() {
+	local dir="$1"
+	local dev="/dev/$(basename $dir)"
+
+	[ -e "$dev" ] && return 0
+
+	local devid="$(cat $dir/dev)"
+	local major="${devid%%:*}"
+	local minor="${devid##*:}"
+	mknod "$dev" c $major $minor
+}
+
+nand_find_volume() {
+	local ubidevdir ubivoldir
+	ubidevdir="/sys/class/ubi/"
+	[ ! -d "$ubidevdir" ] && return 1
+	for ubivoldir in $ubidevdir/${1}_*; do
+		[ ! -d "$ubivoldir" ] && continue
+		if [ "$( cat $ubivoldir/name )" = "$2" ]; then
+			basename $ubivoldir
+			ubi_mknod "$ubivoldir"
+			return 0
+		fi
+	done
+}
+
+nand_find_ubi() {
+	local ubidevdir ubidev mtdnum cmtdnum
+	mtdnum="$( find_mtd_index $1 )"
+	[ ! "$mtdnum" ] && return 1
+	for ubidevdir in /sys/class/ubi/ubi*; do
+		[ ! -e "$ubidevdir/mtd_num" ] && continue
+		cmtdnum="$( cat $ubidevdir/mtd_num )"
+		if [ "$mtdnum" = "$cmtdnum" ]; then
+			ubidev=$( basename $ubidevdir )
+			ubi_mknod "$ubidevdir"
+			echo $ubidev
+			return 0
+		fi
+	done
+}
+
+nand_get_magic_long() {
+	($2 < "$1" | dd bs=4 "skip=${3:-0}" count=1 | hexdump -v -n 4 -e '1/1 "%02x"') 2> /dev/null
+}
+
+get_magic_long_tar() {
+	($2 < "$1" | tar xOf - "$3" | dd bs=4 count=1 | hexdump -v -n 4 -e '1/1 "%02x"') 2> /dev/null
+}
+
+identify() {
+	identify_magic_long $(nand_get_magic_long "$@")
+}
+
+identify_tar() {
+	identify_magic_long $(get_magic_long_tar "$@")
+}
+
+identify_if_gzip() {
+	if [ "$(identify "$1" "cat")" = gzip ]; then echo -n z; fi
+}
+
+nand_restore_config() {
+	local ubidev=$( nand_find_ubi "${CI_ROOT_UBIPART:-$CI_UBIPART}" )
+	local ubivol="$( nand_find_volume $ubidev rootfs_data )"
+	if [ ! "$ubivol" ]; then
+		ubivol="$( nand_find_volume $ubidev "$CI_ROOTPART" )"
+		if [ ! "$ubivol" ]; then
+			echo "cannot find ubifs data volume"
+			return 1
+		fi
+	fi
+	mkdir /tmp/new_root
+	if ! mount -t ubifs /dev/$ubivol /tmp/new_root; then
+		echo "cannot mount ubifs volume $ubivol"
+		rmdir /tmp/new_root
+		return 1
+	fi
+	if mv "$1" "/tmp/new_root/$BACKUP_FILE"; then
+		if umount /tmp/new_root; then
+			echo "configuration saved"
+			rmdir /tmp/new_root
+			return 0
+		fi
+	else
+		umount /tmp/new_root
+	fi
+	echo "could not save configuration to ubifs volume $ubivol"
+	rmdir /tmp/new_root
+	return 1
+}
+
+nand_remove_ubiblock() {
+	local ubivol="$1"
+
+	local ubiblk="ubiblock${ubivol:3}"
+	if [ -e "/dev/$ubiblk" ]; then
+		umount "/dev/$ubiblk" 2>/dev/null && echo "unmounted /dev/$ubiblk" || :
+		if ! ubiblock -r "/dev/$ubivol"; then
+			echo "cannot remove $ubiblk"
+			return 1
+		fi
+	fi
+}
+
+nand_attach_ubi() {
+	local ubipart="$1"
+	local has_env="${2:-0}"
+
+	local mtdnum="$( find_mtd_index "$ubipart" )"
+	if [ ! "$mtdnum" ]; then
+		>&2 echo "cannot find ubi mtd partition $ubipart"
+		return 1
+	fi
+
+	local ubidev="$( nand_find_ubi "$ubipart" )"
+	if [ ! "$ubidev" ]; then
+		>&2 ubiattach -m "$mtdnum"
+		ubidev="$( nand_find_ubi "$ubipart" )"
+
+		if [ ! "$ubidev" ]; then
+			>&2 ubiformat /dev/mtd$mtdnum -y
+			>&2 ubiattach -m "$mtdnum"
+			ubidev="$( nand_find_ubi "$ubipart" )"
+
+			if [ ! "$ubidev" ]; then
+				>&2 echo "cannot attach ubi mtd partition $ubipart"
+				return 1
+			fi
+
+			if [ "$has_env" -gt 0 ]; then
+				>&2 ubimkvol /dev/$ubidev -n 0 -N ubootenv -s 1MiB
+				>&2 ubimkvol /dev/$ubidev -n 1 -N ubootenv2 -s 1MiB
+			fi
+		fi
+	fi
+
+	echo "$ubidev"
+	return 0
+}
+
+nand_detach_ubi() {
+	local ubipart="$1"
+
+	local mtdnum="$( find_mtd_index "$ubipart" )"
+	if [ ! "$mtdnum" ]; then
+		echo "cannot find ubi mtd partition $ubipart"
+		return 1
+	fi
+
+	local ubidev="$( nand_find_ubi "$ubipart" )"
+	if [ "$ubidev" ]; then
+		for ubivol in $(find /dev -name "${ubidev}_*" -maxdepth 1 | sort); do
+			ubivol="${ubivol:5}"
+			nand_remove_ubiblock "$ubivol" || :
+			umount "/dev/$ubivol" && echo "unmounted /dev/$ubivol" || :
+		done
+		if ! ubidetach -m "$mtdnum"; then
+			echo "cannot detach ubi mtd partition $ubipart"
+			return 1
+		fi
+	fi
+}
+
+nand_upgrade_prepare_ubi() {
+	local rootfs_length="$1"
+	local rootfs_type="$2"
+	local rootfs_data_max="$(fw_printenv -n rootfs_data_max 2> /dev/null)"
+	[ -n "$rootfs_data_max" ] && rootfs_data_max=$((rootfs_data_max))
+
+	local kernel_length="$3"
+	local has_env="${4:-0}"
+	local kern_ubidev
+	local root_ubidev
+
+	[ -n "$rootfs_length" -o -n "$kernel_length" ] || return 1
+
+	if [ -n "$CI_KERN_UBIPART" -a -n "$CI_ROOT_UBIPART" ]; then
+		kern_ubidev="$( nand_attach_ubi "$CI_KERN_UBIPART" "$has_env" )"
+		[ -n "$kern_ubidev" ] || return 1
+		root_ubidev="$( nand_attach_ubi "$CI_ROOT_UBIPART" )"
+		[ -n "$root_ubidev" ] || return 1
+	else
+		kern_ubidev="$( nand_attach_ubi "$CI_UBIPART" "$has_env" )"
+		[ -n "$kern_ubidev" ] || return 1
+		root_ubidev="$kern_ubidev"
+	fi
+
+	local kern_ubivol="$( nand_find_volume $kern_ubidev "$CI_KERNPART" )"
+	local root_ubivol="$( nand_find_volume $root_ubidev "$CI_ROOTPART" )"
+	local data_ubivol="$( nand_find_volume $root_ubidev rootfs_data )"
+	[ "$root_ubivol" = "$kern_ubivol" ] && root_ubivol=
+
+	# remove ubiblocks
+	[ "$kern_ubivol" ] && { nand_remove_ubiblock $kern_ubivol || return 1; }
+	[ "$root_ubivol" ] && { nand_remove_ubiblock $root_ubivol || return 1; }
+	[ "$data_ubivol" ] && { nand_remove_ubiblock $data_ubivol || return 1; }
+
+	# kill volumes
+	[ "$kern_ubivol" ] && ubirmvol /dev/$kern_ubidev -N "$CI_KERNPART" || :
+	[ "$root_ubivol" ] && ubirmvol /dev/$root_ubidev -N "$CI_ROOTPART" || :
+	[ "$data_ubivol" ] && ubirmvol /dev/$root_ubidev -N rootfs_data || :
+
+	# create kernel vol
+	if [ -n "$kernel_length" ]; then
+		if ! ubimkvol /dev/$kern_ubidev -N "$CI_KERNPART" -s $kernel_length; then
+			echo "cannot create kernel volume"
+			return 1;
+		fi
+	fi
+
+	# create rootfs vol
+	if [ -n "$rootfs_length" ]; then
+		local rootfs_size_param
+		if [ "$rootfs_type" = "ubifs" ]; then
+			rootfs_size_param="-m"
+		else
+			rootfs_size_param="-s $rootfs_length"
+		fi
+		if ! ubimkvol /dev/$root_ubidev -N "$CI_ROOTPART" $rootfs_size_param; then
+			echo "cannot create rootfs volume"
+			return 1;
+		fi
+	fi
+
+	# create rootfs_data vol for non-ubifs rootfs
+	if [ "$rootfs_type" != "ubifs" ]; then
+		local rootfs_data_size_param="-m"
+		if [ -n "$rootfs_data_max" ]; then
+			rootfs_data_size_param="-s $rootfs_data_max"
+		fi
+		if ! ubimkvol /dev/$root_ubidev -N rootfs_data $rootfs_data_size_param; then
+			if ! ubimkvol /dev/$root_ubidev -N rootfs_data -m; then
+				echo "cannot initialize rootfs_data volume"
+				return 1
+			fi
+		fi
+	fi
+
+	return 0
+}
+
+# Write the UBI image to MTD ubi partition
+nand_upgrade_ubinized() {
+	local ubi_file="$1"
+	local cmd="$2"
+
+	local ubi_length=$( ($cmd < "$ubi_file" | wc -c) 2> /dev/null)
+
+	nand_detach_ubi "$CI_UBIPART" || return 1
+
+	local mtdnum="$( find_mtd_index "$CI_UBIPART" )"
+	$cmd < "$ubi_file" | ubiformat "/dev/mtd$mtdnum" -S "$ubi_length" -y -f - && ubiattach -m "$mtdnum"
+}
+
+# Write the UBIFS image to UBI rootfs volume
+nand_upgrade_ubifs() {
+	local ubifs_file="$1"
+	local cmd="$2"
+
+	local ubifs_length=$( ($cmd < "$ubifs_file" | wc -c) 2> /dev/null)
+
+	nand_upgrade_prepare_ubi "$ubifs_length" "ubifs" "" "" || return 1
+
+	local ubidev="$( nand_find_ubi "$CI_UBIPART" )"
+	local root_ubivol="$(nand_find_volume $ubidev "$CI_ROOTPART")"
+	$cmd < "$ubifs_file" | ubiupdatevol /dev/$root_ubivol -s "$ubifs_length" -
+}
+
+# Write the FIT image to UBI kernel volume
+nand_upgrade_fit() {
+	local fit_file="$1"
+	local cmd="$2"
+
+	local fit_length=$( ($cmd < "$fit_file" | wc -c) 2> /dev/null)
+
+	nand_upgrade_prepare_ubi "" "" "$fit_length" "1" || return 1
+
+	local fit_ubidev="$(nand_find_ubi "$CI_UBIPART")"
+	local fit_ubivol="$(nand_find_volume $fit_ubidev "$CI_KERNPART")"
+	$cmd < "$fit_file" | ubiupdatevol /dev/$fit_ubivol -s "$fit_length" -
+}
+
+# Write images in the TAR file to MTD partitions and/or UBI volumes as required
+nand_upgrade_tar() {
+	local tar_file="$1"
+	local cmd="${2:-cat}"
+	local jffs2_markers="${CI_JFFS2_CLEAN_MARKERS:-0}"
+
+	# WARNING: This fails if tar contains more than one 'sysupgrade-*' directory.
+	local board_dir="$($cmd < "$tar_file" | tar tf - | grep -m 1 '^sysupgrade-.*/$')"
+	board_dir="${board_dir%/}"
+
+	local kernel_mtd kernel_length
+	if [ "$CI_KERNPART" != "none" ]; then
+		kernel_mtd="$(find_mtd_index "$CI_KERNPART")"
+		kernel_length=$( ($cmd < "$tar_file" | tar xOf - "$board_dir/kernel" | wc -c) 2> /dev/null)
+		[ "$kernel_length" = 0 ] && kernel_length=
+	fi
+	local rootfs_length=$( ($cmd < "$tar_file" | tar xOf - "$board_dir/root" | wc -c) 2> /dev/null)
+	[ "$rootfs_length" = 0 ] && rootfs_length=
+	local rootfs_type
+	[ "$rootfs_length" ] && rootfs_type="$(identify_tar "$tar_file" "$cmd" "$board_dir/root")"
+
+	local ubi_kernel_length
+	if [ "$kernel_length" ]; then
+		if [ "$kernel_mtd" ]; then
+			# On some devices, the raw kernel and ubi partitions overlap.
+			# These devices brick if the kernel partition is erased.
+			# Hence only invalidate kernel for now.
+			dd if=/dev/zero bs=4096 count=1 2> /dev/null | \
+				mtd write - "$CI_KERNPART"
+		else
+			ubi_kernel_length="$kernel_length"
+		fi
+	fi
+
+	local has_env=0
+	nand_upgrade_prepare_ubi "$rootfs_length" "$rootfs_type" "$ubi_kernel_length" "$has_env" || return 1
+
+	if [ "$rootfs_length" ]; then
+		local ubidev="$( nand_find_ubi "${CI_ROOT_UBIPART:-$CI_UBIPART}" )"
+		local root_ubivol="$( nand_find_volume $ubidev "$CI_ROOTPART" )"
+		$cmd < "$tar_file" | tar xOf - "$board_dir/root" | \
+			ubiupdatevol /dev/$root_ubivol -s "$rootfs_length" -
+	fi
+	if [ "$kernel_length" ]; then
+		if [ "$kernel_mtd" ]; then
+			if [ "$jffs2_markers" = 1 ]; then
+				flash_erase -j "/dev/mtd${kernel_mtd}" 0 0
+				$cmd < "$tar_file" | tar xOf - "$board_dir/kernel" | \
+					nandwrite "/dev/mtd${kernel_mtd}" -
+			else
+				$cmd < "$tar_file" | tar xOf - "$board_dir/kernel" | \
+					mtd write - "$CI_KERNPART"
+			fi
+		else
+			local ubidev="$( nand_find_ubi "${CI_KERN_UBIPART:-$CI_UBIPART}" )"
+			local kern_ubivol="$( nand_find_volume $ubidev "$CI_KERNPART" )"
+			$cmd < "$tar_file" | tar xOf - "$board_dir/kernel" | \
+				ubiupdatevol /dev/$kern_ubivol -s "$kernel_length" -
+		fi
+	fi
+
+	return 0
+}
+
+nand_verify_if_gzip_file() {
+	local file="$1"
+	local cmd="$2"
+
+	if [ "$cmd" = zcat ]; then
+		echo "verifying compressed sysupgrade file integrity"
+		if ! gzip -t "$file"; then
+			echo "corrupted compressed sysupgrade file"
+			return 1
+		fi
+	fi
+}
+
+nand_verify_tar_file() {
+	local file="$1"
+	local cmd="$2"
+
+	echo "verifying sysupgrade tar file integrity"
+	if ! $cmd < "$file" | tar xOf - > /dev/null; then
+		echo "corrupted sysupgrade tar file"
+		return 1
+	fi
+}
+
+nand_do_flash_file() {
+	local file="$1"
+	local cmd="$2"
+	local file_type
+
+	[ -z "$cmd" ] && cmd="$(identify_if_gzip "$file")cat"
+	file_type="$(identify "$file" "$cmd" "")"
+
+	[ ! "$(find_mtd_index "$CI_UBIPART")" ] && CI_UBIPART=rootfs
+
+	case "$file_type" in
+		"fit")
+			nand_verify_if_gzip_file "$file" "$cmd" || return 1
+			nand_upgrade_fit "$file" "$cmd"
+			;;
+		"ubi")
+			nand_verify_if_gzip_file "$file" "$cmd" || return 1
+			nand_upgrade_ubinized "$file" "$cmd"
+			;;
+		"ubifs")
+			nand_verify_if_gzip_file "$file" "$cmd" || return 1
+			nand_upgrade_ubifs "$file" "$cmd"
+			;;
+		*)
+			nand_verify_tar_file "$file" "$cmd" || return 1
+			nand_upgrade_tar "$file" "$cmd"
+			;;
+	esac
+}
+
+nand_do_restore_config() {
+	local conf_tar="/tmp/sysupgrade.tgz"
+	[ ! -f "$conf_tar" ] || nand_restore_config "$conf_tar"
+}
+
+# Recognize type of passed file and start the upgrade process
+#
+# Supported firmware containers:
+# 1. Raw file
+# 2. Gzip
+# 3. Custom (requires passing extracting command)
+#
+# Supported data formats:
+# 1. Tar with kernel/rootfs
+# 2. UBI image (built using "ubinized")
+# 3. UBIFS image (to update UBI volume with)
+# 4. FIT image (to update UBI volume with)
+#
+# $(1): firmware file path
+# $(2): (optional) pipe command to extract firmware
+nand_do_upgrade() {
+	local file="$1"
+	local cmd="$2"
+
+	sync
+	nand_do_flash_file "$file" "$cmd" && nand_do_upgrade_success
+	nand_do_upgrade_failed
+}
+
+nand_do_upgrade_success() {
+	if nand_do_restore_config && sync; then
+		echo "sysupgrade successful"
+		umount -a
+		reboot -f
+	fi
+	nand_do_upgrade_failed
+}
+
+nand_do_upgrade_failed() {
+	sync
+	echo "sysupgrade failed"
+	# Should we reboot or bring up some failsafe mode instead?
+	umount -a
+	reboot -f
+}
+
+# Check if passed file is a valid one for NAND sysupgrade.
+# Currently it accepts 4 types of files:
+# 1) UBI: a ubinized image containing required UBI volumes.
+# 2) UBIFS: a UBIFS rootfs volume image.
+# 3) FIT: a FIT image containing kernel and rootfs.
+# 4) TAR: an archive that includes directory "sysupgrade-${BOARD_NAME}" containing
+#         a non-empty "CONTROL" file and required partition and/or volume images.
+#
+# You usually want to call this function in platform_check_image.
+#
+# $(1): board name, used in case of passing TAR file
+# $(2): file to be checked
+nand_do_platform_check() {
+	local board_name="$1"
+	local file="$2"
+
+	local cmd="$(identify_if_gzip "$file")cat"
+	local file_type="$(identify "$file" "$cmd" "")"
+	local control_length=$( ($cmd < "$file" | tar xOf - "sysupgrade-${board_name//,/_}/CONTROL" | wc -c) 2> /dev/null)
+
+	if [ "$control_length" = 0 ]; then
+		control_length=$( ($cmd < "$file" | tar xOf - "sysupgrade-${board_name//_/,}/CONTROL" | wc -c) 2> /dev/null)
+	fi
+
+	if [ "$control_length" != 0 ]; then
+		nand_verify_tar_file "$file" "$cmd" || return 1
+	else
+		nand_verify_if_gzip_file "$file" "$cmd" || return 1
+		if [ "$file_type" != "fit" -a "$file_type" != "ubi" -a "$file_type" != "ubifs" ]; then
+			echo "invalid sysupgrade file"
+			return 1
+		fi
+	fi
+
+	return 0
+}
diff --git a/package/base-files/files/lib/upgrade/stage2 b/package/base-files/files/lib/upgrade/stage2
new file mode 100755
index 0000000..5ce0b35
--- /dev/null
+++ b/package/base-files/files/lib/upgrade/stage2
@@ -0,0 +1,175 @@
+#!/bin/sh
+
+. /lib/functions.sh
+. /lib/functions/system.sh
+
+export IMAGE="$1"
+COMMAND="$2"
+
+export INTERACTIVE=0
+export VERBOSE=1
+export CONFFILES=/tmp/sysupgrade.conffiles
+
+RAMFS_COPY_BIN=		# extra programs for temporary ramfs root
+RAMFS_COPY_DATA=	# extra data files
+
+include /lib/upgrade
+
+
+supivot() { # <new_root> <old_root>
+	/bin/mount | grep "on $1 type" 2>&- 1>&- || /bin/mount -o bind $1 $1
+	mkdir -p $1$2 $1/proc $1/sys $1/dev $1/tmp $1/overlay && \
+	/bin/mount -o noatime,move /proc $1/proc && \
+	pivot_root $1 $1$2 || {
+		/bin/umount -l $1 $1
+		return 1
+	}
+
+	/bin/mount -o noatime,move $2/sys /sys
+	/bin/mount -o noatime,move $2/dev /dev
+	/bin/mount -o noatime,move $2/tmp /tmp
+	/bin/mount -o noatime,move $2/overlay /overlay 2>&-
+	return 0
+}
+
+switch_to_ramfs() {
+	RAMFS_COPY_LOSETUP="$(command -v /usr/sbin/losetup)"
+	RAMFS_COPY_LVM="$(command -v lvm)"
+
+	for binary in \
+		/bin/busybox /bin/ash /bin/sh /bin/mount /bin/umount	\
+		pivot_root mount_root reboot sync kill sleep		\
+		md5sum hexdump cat zcat dd tar gzip			\
+		ls basename find cp mv rm mkdir rmdir mknod touch chmod \
+		'[' printf wc grep awk sed cut sort tail		\
+		mtd partx losetup mkfs.ext4 nandwrite flash_erase	\
+		ubiupdatevol ubiattach ubiblock ubiformat		\
+		ubidetach ubirsvol ubirmvol ubimkvol			\
+		snapshot snapshot_tool date logger			\
+		/usr/sbin/fw_printenv /usr/bin/fwtool			\
+		$RAMFS_COPY_LOSETUP $RAMFS_COPY_LVM			\
+		$RAMFS_COPY_BIN
+	do
+		local file="$(command -v "$binary" 2>/dev/null)"
+		[ -n "$file" ] && install_bin "$file"
+	done
+	install_file /etc/resolv.conf /lib/*.sh /lib/functions/*.sh	\
+		/lib/upgrade/*.sh /lib/upgrade/do_stage2 		\
+		/usr/share/libubox/jshn.sh /usr/sbin/fw_setenv		\
+		/etc/fw_env.config $RAMFS_COPY_DATA
+
+	mkdir -p $RAM_ROOT/var/lock
+
+	[ -L "/lib64" ] && ln -s /lib $RAM_ROOT/lib64
+
+	supivot $RAM_ROOT /mnt || {
+		v "Failed to switch over to ramfs. Please reboot."
+		exit 1
+	}
+
+	/bin/mount -o remount,ro /mnt
+	/bin/umount -l /mnt
+
+	grep -e "^/dev/dm-.*" -e "^/dev/loop.*" /proc/mounts | while read bdev mp _r; do
+		umount $mp
+	done
+
+	[ "$RAMFS_COPY_LOSETUP" ] && losetup -D
+	[ "$RAMFS_COPY_LVM" ] && {
+		mkdir -p /tmp/lvm/cache
+		$RAMFS_COPY_LVM vgchange -aln --ignorelockingfailure
+	}
+
+	grep /overlay /proc/mounts > /dev/null && {
+		/bin/mount -o noatime,remount,ro /overlay
+		/bin/umount -l /overlay
+	}
+}
+
+kill_remaining() { # [ <signal> [ <loop> ] ]
+	local loop_limit=10
+
+	local sig="${1:-TERM}"
+	local loop="${2:-0}"
+	local run=true
+	local stat
+	local proc_ppid=$(cut -d' ' -f4  /proc/$$/stat)
+
+	v "Sending $sig to remaining processes ..."
+
+	while $run; do
+		run=false
+		for stat in /proc/[0-9]*/stat; do
+			[ -f "$stat" ] || continue
+
+			local pid name state ppid rest
+			read pid rest < $stat
+			name="${rest#\(}" ; rest="${name##*\) }" ; name="${name%\)*}"
+			set -- $rest ; state="$1" ; ppid="$2"
+
+			# Skip PID1, our parent, ourself and our children
+			[ $pid -ne 1 -a $pid -ne $proc_ppid -a $pid -ne $$ -a $ppid -ne $$ ] || continue
+
+			[ -f "/proc/$pid/cmdline" ] || continue
+
+			local cmdline
+			read cmdline < /proc/$pid/cmdline
+
+			# Skip kernel threads
+			[ -n "$cmdline" ] || continue
+
+			v "Sending signal $sig to $name ($pid)"
+			kill -$sig $pid 2>/dev/null
+
+			[ $loop -eq 1 ] && sleep 2 && run=true
+		done
+
+		let loop_limit--
+		[ $loop_limit -eq 0 ] && {
+			v "Failed to kill all processes."
+			exit 1
+		}
+	done
+}
+
+indicate_upgrade
+
+while read -r a b c; do
+	case "$a" in
+		MemT*) mem="$b" ;; esac
+done < /proc/meminfo
+
+[ "$mem" -gt 32768 ] && \
+	skip_services="dnsmasq log network"
+for service in /etc/init.d/*; do
+	service=${service##*/}
+
+	case " $skip_services " in
+		*" $service "*) continue ;; esac
+
+	ubus call service delete '{ "name": "'"$service"'" }' 2>/dev/null
+done
+
+killall -9 telnetd 2>/dev/null
+killall -9 dropbear 2>/dev/null
+killall -9 ash 2>/dev/null
+
+kill_remaining TERM
+sleep 4
+kill_remaining KILL 1
+
+sleep 6
+
+echo 3 > /proc/sys/vm/drop_caches
+
+if [ -n "$IMAGE" ] && type 'platform_pre_upgrade' >/dev/null 2>/dev/null; then
+	platform_pre_upgrade "$IMAGE"
+fi
+
+if [ -n "$(rootfs_type)" ]; then
+	v "Switching to ramdisk..."
+	switch_to_ramfs
+fi
+
+# Exec new shell from ramfs
+exec /bin/busybox ash -c "$COMMAND"
diff --git a/package/base-files/files/lib/upgrade/tar.sh b/package/base-files/files/lib/upgrade/tar.sh
new file mode 100644
index 0000000..a9d1d55
--- /dev/null
+++ b/package/base-files/files/lib/upgrade/tar.sh
@@ -0,0 +1,71 @@
+# SPDX-License-Identifier: GPL-2.0-or-later OR MIT
+
+# Example usage:
+#
+# {
+#         tar_print_member "date.txt" "It's $(date +"%Y")"
+#         tar_print_trailer
+# } > test.tar
+
+__tar_print_padding() {
+	dd if=/dev/zero bs=1 count=$1 2>/dev/null
+}
+
+tar_print_member() {
+	local name="$1"
+	local content="$2"
+	local mtime="${3:-$(date +%s)}"
+	local mode=644
+	local uid=0
+	local gid=0
+	local size=${#content}
+	local type=0
+	local link=""
+	local username="root"
+	local groupname="root"
+
+	# 100 byte of padding bytes, using 0x01 since the shell does not tolerate null bytes in strings
+	local pad=$'\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1'
+
+	# validate name (strip leading slash if present)
+	name=${name#/}
+
+	# truncate string header values to their maximum length
+	name=${name:0:100}
+	link=${link:0:100}
+	username=${username:0:32}
+	groupname=${groupname:0:32}
+
+	# construct header part before checksum field
+	local header1="${name}${pad:0:$((100 - ${#name}))}"
+	header1="${header1}$(printf '%07d\1' $mode)"
+	header1="${header1}$(printf '%07o\1' $uid)"
+	header1="${header1}$(printf '%07o\1' $gid)"
+	header1="${header1}$(printf '%011o\1' $size)"
+	header1="${header1}$(printf '%011o\1' $mtime)"
+
+	# construct header part after checksum field
+	local header2="$(printf '%d' $type)"
+	header2="${header2}${link}${pad:0:$((100 - ${#link}))}"
+	header2="${header2}ustar  ${pad:0:1}"
+	header2="${header2}${username}${pad:0:$((32 - ${#username}))}"
+	header2="${header2}${groupname}${pad:0:$((32 - ${#groupname}))}"
+
+	# calculate checksum over header fields
+	local checksum=0
+	for byte in $(printf '%s%8s%s' "$header1" "" "$header2" | tr '\1' '\0' | hexdump -ve '1/1 "%u "'); do
+		checksum=$((checksum + byte))
+	done
+
+	# print member header, padded to 512 byte
+	printf '%s%06o\0 %s' "$header1" $checksum "$header2" | tr '\1' '\0'
+	__tar_print_padding 183
+
+	# print content data, padded to multiple of 512 byte
+	printf "%s" "$content"
+	__tar_print_padding $((512 - (size % 512)))
+}
+
+tar_print_trailer() {
+	__tar_print_padding 1024
+}
diff --git a/package/base-files/files/rom/note b/package/base-files/files/rom/note
new file mode 100644
index 0000000..1746eb0
--- /dev/null
+++ b/package/base-files/files/rom/note
@@ -0,0 +1,3 @@
+SQUASHFS USERS:
+After firstboot has been run, / will be jffs2 and /rom will be squashfs
+(* except when in failsafe)
diff --git a/package/base-files/files/sbin/firstboot b/package/base-files/files/sbin/firstboot
new file mode 100755
index 0000000..d9af57d
--- /dev/null
+++ b/package/base-files/files/sbin/firstboot
@@ -0,0 +1,3 @@
+#!/bin/sh
+
+/sbin/jffs2reset $@
diff --git a/package/base-files/files/sbin/hotplug-call b/package/base-files/files/sbin/hotplug-call
new file mode 100755
index 0000000..f595b9e
--- /dev/null
+++ b/package/base-files/files/sbin/hotplug-call
@@ -0,0 +1,18 @@
+#!/bin/sh
+# Copyright (C) 2006-2016 OpenWrt.org
+
+export HOTPLUG_TYPE="$1"
+
+. /lib/functions.sh
+
+PATH="%PATH%"
+LOGNAME=root
+USER=root
+export PATH LOGNAME USER
+export DEVICENAME="${DEVPATH##*/}"
+
+if [ \! -z "$1" -a -d /etc/hotplug.d/$1 ]; then
+	for script in $(ls /etc/hotplug.d/$1/* 2>&-); do (
+		[ -f $script ] && . $script
+	); done
+fi
diff --git a/package/base-files/files/sbin/led.sh b/package/base-files/files/sbin/led.sh
new file mode 100755
index 0000000..d750f06
--- /dev/null
+++ b/package/base-files/files/sbin/led.sh
@@ -0,0 +1,25 @@
+#!/bin/sh
+# (C) 2008 openwrt.org
+
+. /lib/functions.sh
+ACTION=$1
+NAME=$2
+do_led() {
+	local name
+	local sysfs
+	config_get name $1 name
+	config_get sysfs $1 sysfs
+	[ "$name" = "$NAME" -o "$sysfs" = "$NAME" -a -e "/sys/class/leds/${sysfs}" ] && {
+		[ "$ACTION" = "set" ] &&
+			echo 1 >/sys/class/leds/${sysfs}/brightness \
+			|| echo 0 >/sys/class/leds/${sysfs}/brightness
+		exit 0
+	}
+}
+
+[ "$1" = "clear" -o "$1" = "set" ] &&
+	[ -n "$2" ] &&{
+		config_load system
+		config_foreach do_led
+		exit 1
+	}
diff --git a/package/base-files/files/sbin/pkg_check b/package/base-files/files/sbin/pkg_check
new file mode 100755
index 0000000..28e8792
--- /dev/null
+++ b/package/base-files/files/sbin/pkg_check
@@ -0,0 +1,130 @@
+#!/bin/sh
+#
+# Package checksums checking script
+# (C) 2018 CZ.NIC, z.s.p.o.
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+
+ERRFATAL="no"
+QUIET="yes"
+MISSING=""
+SUMMARY=""
+NL="
+"
+
+# Arguments parsing
+while expr "x$1" : "x-" > /dev/null; do
+	if [ "x$1" = "x-s" ]; then
+		ERRFATAL="yes"
+		shift
+	elif [ "x$1" = "x-v" ]; then
+		QUIET="	no"
+		shift
+	else
+		echo "Usage: $(basename $0) [-s] [-v] [pkg1 pkg2 ...]"
+		echo
+		echo "   -s   Stop on first change"
+		echo "   -v   Verbose"
+		if [ "x$1" = "x-h" ]; then
+			exit 0
+		else
+			echo
+			echo "ERROR: Unknown option '$1'"
+			exit 1
+		fi
+	fi
+done
+
+# Check all packages by default
+if [ -z "$1" ]; then
+	set $(cd /usr/lib/opkg/info/; for i in *.files-sha256sum; do basename $i .files-sha256sum; done)
+fi
+
+# Iterate over packages
+while [ "$1" ]; do
+	if [ \! -f "/usr/lib/opkg/info/$1.files-sha256sum" ]; then
+		if [ "$ERRFATAL" = no ]; then
+			echo " * No checksums for $1 - skipping"
+			echo
+		else
+			echo " * No checksums for $1 - exiting"
+			exit 1
+		fi
+		if [ -z "$MISSING" ]; then
+			MISSING="$1"
+		else
+			MISSING="$MISSING, $1"
+		fi
+		shift
+		continue
+	fi
+	[ $QUIET = yes ] || echo " * Checking package $1:"
+	ERR=""
+	CHECK="$(sha256sum -c /usr/lib/opkg/info/$1.files-sha256sum 2> /dev/null)"
+
+	# Are the changed files config files?
+	if [ $? -ne 0 ] && [ "$(cat "/usr/lib/opkg/info/$1.files-sha256sum")" ]; then
+		NEWCHECK="$(echo "$CHECK" | grep '^.*: OK$')"
+		for i in $(echo "$CHECK" | sed -n 's|^\(.*\): FAILED$|\1|p'); do
+			if [ "$(grep "^$i\$" "/usr/lib/opkg/info/$1.conffiles" 2> /dev/null)" ] || \
+			   [ "$(echo "$i" | grep "^/etc/uci-defaults/")" ]; then
+				NEWCHECK="${NEWCHECK}${NL}${i}: CONFIGURED"
+			else
+				NEWCHECK="${NEWCHECK}${NL}${i}: FAILED"
+				ERR="y"
+			fi
+		done
+		CHECK="$NEWCHECK"
+	fi
+
+	# Do we have changed files or not?
+	if [ -z "$ERR" ]; then
+		[ $QUIET = yes ] || [ ! -s "/usr/lib/opkg/info/$1.files-sha256sum" ] || echo "$CHECK" | sed 's|^|   - |'
+		[ $QUIET = yes ] || echo " * Package $1 is ok"
+		[ $QUIET = yes ] || echo
+	else
+		if [ $QUIET = yes ]; then
+			echo " * Changes found in package $1:"
+			echo "$CHECK" | sed -n 's|^\(.*:[[:blank:]]*FAILED\)$|   - \1|p'
+		else
+			echo "$CHECK" | sed 's|^|   - |'
+			echo " * Changes found in package $1!"
+		fi
+		if [ "$ERRFATAL" = yes ]; then
+			echo
+			echo "Exiting on first change found!"
+			exit 1
+		fi
+		for i in $(echo "$CHECK" | sed -n 's|^\(.*\): FAILED$|\1|p'); do
+			SUMMARY="${SUMMARY}${NL} - $1: $i"
+		done
+		echo
+	fi
+	shift
+done
+
+# If there are changed files, report them
+if [ "$SUMMARY" ]; then
+	echo "Some packages contain changed files!"
+	echo "Maybe something worth looking into?"
+	echo "Here is the list of packages and changed files:"
+	echo "$SUMMARY"
+fi
+if [ "$MISSING" ]; then
+	echo "Following packages are missing checksums: $MISSING"
+fi
+if [ "$MISSING" ] || [ "$SUMMARY" ]; then
+	exit 1
+fi
diff --git a/package/base-files/files/sbin/sysupgrade b/package/base-files/files/sbin/sysupgrade
new file mode 100755
index 0000000..611d883
--- /dev/null
+++ b/package/base-files/files/sbin/sysupgrade
@@ -0,0 +1,422 @@
+#!/bin/sh
+
+. /lib/functions.sh
+. /lib/functions/system.sh
+. /usr/share/libubox/jshn.sh
+
+# File-local constants
+CONF_TAR=/tmp/sysupgrade.tgz
+ETCBACKUP_DIR=/etc/backup
+INSTALLED_PACKAGES=${ETCBACKUP_DIR}/installed_packages.txt
+COMMAND=/lib/upgrade/do_stage2
+
+# File-local globals
+SAVE_OVERLAY=0
+SAVE_OVERLAY_PATH=
+SAVE_PARTITIONS=1
+SAVE_INSTALLED_PKGS=0
+SKIP_UNCHANGED=0
+CONF_IMAGE=
+CONF_BACKUP_LIST=0
+CONF_BACKUP=
+CONF_RESTORE=
+NEED_IMAGE=
+HELP=0
+TEST=0
+
+# Globals accessed in other files
+export MTD_ARGS=""
+export MTD_CONFIG_ARGS=""
+export INTERACTIVE=0
+export VERBOSE=1
+export SAVE_CONFIG=1
+export IGNORE_MINOR_COMPAT=0
+export FORCE=0
+export CONFFILES=/tmp/sysupgrade.conffiles
+
+# parse options
+while [ -n "$1" ]; do
+	case "$1" in
+		-i) export INTERACTIVE=1;;
+		-v) export VERBOSE="$(($VERBOSE + 1))";;
+		-q) export VERBOSE="$(($VERBOSE - 1))";;
+		-n) export SAVE_CONFIG=0;;
+		-c) SAVE_OVERLAY=1 SAVE_OVERLAY_PATH=/etc;;
+		-o) SAVE_OVERLAY=1 SAVE_OVERLAY_PATH=/;;
+		-p) SAVE_PARTITIONS=0;;
+		-k) SAVE_INSTALLED_PKGS=1;;
+		-u) SKIP_UNCHANGED=1;;
+		-b|--create-backup) CONF_BACKUP="$2" NEED_IMAGE=1; shift;;
+		-r|--restore-backup) CONF_RESTORE="$2" NEED_IMAGE=1; shift;;
+		-l|--list-backup) CONF_BACKUP_LIST=1;;
+		-f) CONF_IMAGE="$2"; shift;;
+		-F|--force) export FORCE=1;;
+		-T|--test) TEST=1;;
+		-h|--help) HELP=1; break;;
+		--ignore-minor-compat-version) export IGNORE_MINOR_COMPAT=1;;
+		-*)
+			echo "Invalid option: $1" >&2
+			exit 1
+		;;
+		*) break;;
+	esac
+	shift;
+done
+
+print_help() {
+	cat <<EOF
+Usage: $0 [<upgrade-option>...] <image file or URL>
+       $0 [-q] [-i] [-c] [-u] [-o] [-k] <backup-command> <file>
+
+upgrade-option:
+	-f <config>  restore configuration from .tar.gz (file or url)
+	-i           interactive mode
+	-c           attempt to preserve all changed files in /etc/
+	-o           attempt to preserve all changed files in /, except those
+	             from packages but including changed confs.
+	-u           skip from backup files that are equal to those in /rom
+	-n           do not save configuration over reflash
+	-p           do not attempt to restore the partition table after flash.
+	-k           include in backup a list of current installed packages at
+	             $INSTALLED_PACKAGES
+	-T | --test
+	             Verify image and config .tar.gz but do not actually flash.
+	-F | --force
+	             Flash image even if image checks fail, this is dangerous!
+	--ignore-minor-compat-version
+		     Flash image even if the minor compat version is incompatible.
+	-q           less verbose
+	-v           more verbose
+	-h | --help  display this help
+
+backup-command:
+	-b | --create-backup <file>
+	             create .tar.gz of files specified in sysupgrade.conf
+	             then exit. Does not flash an image. If file is '-',
+	             i.e. stdout, verbosity is set to 0 (i.e. quiet).
+	-r | --restore-backup <file>
+	             restore a .tar.gz created with sysupgrade -b
+	             then exit. Does not flash an image. If file is '-',
+	             the archive is read from stdin.
+	-l | --list-backup
+	             list the files that would be backed up when calling
+	             sysupgrade -b. Does not create a backup file.
+
+EOF
+}
+
+IMAGE="$1"
+
+if [ $HELP -gt 0 ]; then
+	print_help
+	exit 0
+fi
+
+if [ -z "$IMAGE" -a -z "$NEED_IMAGE" -a $CONF_BACKUP_LIST -eq 0 ]; then
+	print_help
+	exit 1
+fi
+
+[ -n "$IMAGE" -a -n "$NEED_IMAGE" ] && {
+	cat <<-EOF
+		-b|--create-backup and -r|--restore-backup do not perform a firmware upgrade.
+		Do not specify both -b|-r and a firmware image.
+	EOF
+	exit 1
+}
+
+# prevent messages from clobbering the tarball when using stdout
+[ "$CONF_BACKUP" = "-" ] && export VERBOSE=0
+
+
+list_conffiles() {
+	if [ -f /usr/lib/opkg/status ]; then
+		awk '
+			BEGIN { conffiles = 0 }
+			/^Conffiles:/ { conffiles = 1; next }
+			!/^ / { conffiles = 0; next }
+			conffiles == 1 { print }
+		' /usr/lib/opkg/status
+	elif [ -d /lib/apk/packages ]; then
+		conffiles=""
+		for file in /lib/apk/packages/*.conffiles_static; do
+			conffiles="$(echo -e "$(cat $file)\n$conffiles")"
+		done
+		echo "$conffiles"
+	fi
+}
+
+list_changed_conffiles() {
+	# Cannot handle spaces in filenames - but opkg cannot either...
+	list_conffiles | while read file csum; do
+		[ -r "$file" ] || continue
+
+		echo "${csum}  ${file}" | busybox sha256sum -sc - || echo "$file"
+	done
+}
+
+list_static_conffiles() {
+	local filter=$1
+
+	find $(sed -ne '/^[[:space:]]*$/d; /^#/d; p' \
+		/etc/sysupgrade.conf /lib/upgrade/keep.d/* 2>/dev/null) \
+		\( -type f -o -type l \) $filter 2>/dev/null
+}
+
+build_list_of_backup_config_files() {
+	local file="$1"
+
+	( list_static_conffiles "$find_filter"; list_changed_conffiles ) |
+		sort -u > "$file"
+	return 0
+}
+
+build_list_of_backup_overlay_files() {
+	local file="$1"
+
+	local packagesfiles=$1.packagesfiles
+	touch "$packagesfiles"
+
+	if [ "$SAVE_OVERLAY_PATH" = / ]; then
+		local conffiles=$1.conffiles
+		local keepfiles=$1.keepfiles
+
+		list_conffiles | cut -f2 -d ' ' | sort -u > "$conffiles"
+
+		# backup files from /etc/sysupgrade.conf and /lib/upgrade/keep.d, but
+		# ignore those aready controlled by opkg conffiles
+		list_static_conffiles | sort -u |
+			grep -h -v -x -F -f $conffiles > "$keepfiles"
+
+		# backup conffiles, but only those changed if '-u'
+		[ $SKIP_UNCHANGED = 1 ] &&
+			list_changed_conffiles | sort -u > "$conffiles"
+
+		# do not backup files from packages, except those listed
+		# in conffiles and keep.d
+		{
+			find /usr/lib/opkg/info -type f -name "*.list" -exec cat {} \;
+			find /usr/lib/opkg/info -type f -name "*.control" -exec sed \
+				-ne '/^Alternatives/{s/^Alternatives: //;s/, /\n/g;p}' {} \; |
+				cut -f2 -d:
+		} |  grep -v -x -F -f $conffiles |
+		     grep -v -x -F -f $keepfiles | sort -u > "$packagesfiles"
+		rm -f "$keepfiles" "$conffiles"
+	fi
+
+	# busybox grep bug when file is empty
+	[ -s "$packagesfiles" ] || echo > $packagesfiles
+
+	( cd /overlay/upper/; find .$SAVE_OVERLAY_PATH \( -type f -o -type l \) $find_filter | sed \
+		-e 's,^\.,,' \
+		-e '\,^/etc/board.json$,d' \
+		-e '\,/[^/]*-opkg$,d' \
+		-e '\,^/etc/urandom.seed$,d' \
+		-e "\,^$INSTALLED_PACKAGES$,d" \
+		-e '\,^/usr/lib/opkg/.*,d' \
+	) | grep -v -x -F -f $packagesfiles > "$file"
+
+	rm -f "$packagesfiles"
+
+	return 0
+}
+
+if [ $SAVE_OVERLAY = 1 ]; then
+	[ ! -d /overlay/upper/etc ] && {
+		echo "Cannot find '/overlay/upper/etc', required for '-c' or '-o'" >&2
+		exit 1
+	}
+	sysupgrade_init_conffiles="build_list_of_backup_overlay_files"
+else
+	sysupgrade_init_conffiles="build_list_of_backup_config_files"
+fi
+
+find_filter=""
+if [ $SKIP_UNCHANGED = 1 ]; then
+	[ ! -d /rom/ ] && {
+		echo "'/rom/' is required by '-u'"
+		exit 1
+	}
+	find_filter='( ( -exec test -e /rom/{} ; -exec cmp -s /{} /rom/{} ; ) -o -print )'
+fi
+
+include /lib/upgrade
+
+create_backup_archive() {
+	local conf_tar="$1"
+	local disabled
+	local err
+
+	[ "$(rootfs_type)" = "tmpfs" ] && {
+		echo "Cannot save config while running from ramdisk." >&2
+		ask_bool 0 "Abort" && exit
+		return 0
+	}
+	run_hooks "$CONFFILES" $sysupgrade_init_conffiles
+	ask_bool 0 "Edit config file list" && vi "$CONFFILES"
+
+	[ "$conf_tar" != "-" ] || conf_tar=""
+
+	v "Saving config files..."
+	[ "$VERBOSE" -gt 1 ] && TAR_V="v" || TAR_V=""
+	sed -i -e 's,^/,,' "$CONFFILES"
+	set -o pipefail
+	{
+		local ret=0
+
+		if [ $ret -eq 0 ]; then
+			for service in /etc/init.d/*; do
+				if ! $service enabled; then
+				disabled="$disabled$service disable\n"
+				fi
+			done
+			disabled="$disabled\nexit 0"
+			tar_print_member "/etc/uci-defaults/10_disable_services" "$(echo -e $disabled)" || ret=1
+		fi
+
+		# Part of archive with installed packages info
+		if [ $ret -eq 0 ]; then
+			if [ "$SAVE_INSTALLED_PKGS" -eq 1 ]; then
+				# Format: pkg-name<TAB>{rom,overlay,unknown}
+				# rom is used for pkgs in /rom, even if updated later
+				tar_print_member "$INSTALLED_PACKAGES" "$(find /usr/lib/opkg/info -name "*.control" \( \
+					\( -exec test -f /rom/{} \; -exec echo {} rom \; \) -o \
+					\( -exec test -f /overlay/upper/{} \; -exec echo {} overlay \; \) -o \
+					\( -exec echo {} unknown \; \) \
+					\) | sed -e 's,.*/,,;s/\.control /\t/')" || ret=1
+			fi
+		fi
+
+		# Rest of archive with config files and ending padding
+		if [ $ret -eq 0 ]; then
+			tar c${TAR_V} -C / -T "$CONFFILES" || ret=1
+		fi
+
+		[ $ret -eq 0 ]
+	} | gzip > "${conf_tar:-/proc/self/fd/1}"
+	err=$?
+	set +o pipefail
+
+	if [ "$err" -ne 0 ]; then
+		echo "Failed to create the configuration backup."
+		[ -f "$conf_tar" ] && rm -f "$conf_tar"
+	fi
+
+	rm -f "$CONFFILES"
+
+	return "$err"
+}
+
+if [ $CONF_BACKUP_LIST -eq 1 ]; then
+	run_hooks "$CONFFILES" $sysupgrade_init_conffiles
+	[ "$SAVE_INSTALLED_PKGS" -eq 1 ] && echo ${INSTALLED_PACKAGES} >> "$CONFFILES"
+	cat "$CONFFILES"
+	rm -f "$CONFFILES"
+	exit 0
+fi
+
+if [ -n "$CONF_BACKUP" ]; then
+	create_backup_archive "$CONF_BACKUP"
+	exit
+fi
+
+if [ -n "$CONF_RESTORE" ]; then
+	if [ "$CONF_RESTORE" != "-" ] && [ ! -f "$CONF_RESTORE" ]; then
+		echo "Backup archive '$CONF_RESTORE' not found." >&2
+		exit 1
+	fi
+
+	[ "$VERBOSE" -gt 1 ] && TAR_V="v" || TAR_V=""
+	v "Restoring config files..."
+	if [ "$(type -t platform_restore_backup)" == 'platform_restore_backup' ]; then
+		platform_restore_backup "$TAR_V"
+	else
+		tar -C / -x${TAR_V}zf "$CONF_RESTORE"
+	fi
+	exit $?
+fi
+
+type platform_check_image >/dev/null 2>/dev/null || {
+	echo "Firmware upgrade is not implemented for this platform." >&2
+	exit 1
+}
+
+case "$IMAGE" in
+	http://*|\
+	https://*)
+		wget -O/tmp/sysupgrade.img "$IMAGE" || exit 1
+		IMAGE=/tmp/sysupgrade.img
+		;;
+esac
+
+IMAGE="$(readlink -f "$IMAGE")"
+
+case "$IMAGE" in
+	'')
+		echo "Image file not found." >&2
+		exit 1
+		;;
+	/tmp/*)	;;
+	*)
+		v "Image not in /tmp, copying..."
+		cp -f "$IMAGE" /tmp/sysupgrade.img
+		IMAGE=/tmp/sysupgrade.img
+		;;
+esac
+
+json_load "$(/usr/libexec/validate_firmware_image "$IMAGE")" || {
+	echo "Failed to check image"
+	exit 1
+}
+json_get_var valid "valid"
+[ "$valid" -eq 0 ] && {
+	if [ $FORCE -eq 1 ]; then
+		echo "Image check failed but --force given - will update anyway!" >&2
+	else
+		echo "Image check failed." >&2
+		exit 1
+	fi
+}
+
+if [ -n "$CONF_IMAGE" ]; then
+	case "$(get_magic_word $CONF_IMAGE cat)" in
+		# .gz files
+		1f8b) ;;
+		*)
+			echo "Invalid config file. Please use only .tar.gz files" >&2
+			exit 1
+		;;
+	esac
+	get_image "$CONF_IMAGE" "cat" > "$CONF_TAR"
+	export SAVE_CONFIG=1
+elif ask_bool $SAVE_CONFIG "Keep config files over reflash"; then
+	[ $TEST -eq 1 ] || create_backup_archive "$CONF_TAR" || exit
+	export SAVE_CONFIG=1
+else
+	[ $TEST -eq 1 ] || rm -f "$CONF_TAR"
+	export SAVE_CONFIG=0
+fi
+
+if [ $TEST -eq 1 ]; then
+	exit 0
+fi
+
+install_bin /sbin/upgraded
+v "Commencing upgrade. Closing all shell sessions."
+
+if [ -n "$FAILSAFE" ]; then
+	printf '%s\x00%s\x00%s' "$RAM_ROOT" "$IMAGE" "$COMMAND" >/tmp/sysupgrade
+	lock -u /tmp/.failsafe
+else
+	json_init
+	json_add_string prefix "$RAM_ROOT"
+	json_add_string path "$IMAGE"
+	[ $FORCE -eq 1 ] && json_add_boolean force 1
+	[ $SAVE_CONFIG -eq 1 ] && json_add_string backup "$CONF_TAR"
+	json_add_string command "$COMMAND"
+	json_add_object options
+	json_add_int save_partitions "$SAVE_PARTITIONS"
+	json_close_object
+
+	ubus call system sysupgrade "$(json_dump)"
+fi
diff --git a/package/base-files/files/usr/lib/os-release b/package/base-files/files/usr/lib/os-release
new file mode 100644
index 0000000..12db2c0
--- /dev/null
+++ b/package/base-files/files/usr/lib/os-release
@@ -0,0 +1,19 @@
+NAME="%D"
+VERSION="%V"
+ID="%d"
+ID_LIKE="lede openwrt"
+PRETTY_NAME="%D %V"
+VERSION_ID="%v"
+HOME_URL="%u"
+BUG_URL="%b"
+SUPPORT_URL="%s"
+BUILD_ID="%R"
+OPENWRT_BOARD="%S"
+OPENWRT_ARCH="%A"
+OPENWRT_TAINTS="%t"
+OPENWRT_DEVICE_MANUFACTURER="%M"
+OPENWRT_DEVICE_MANUFACTURER_URL="%m"
+OPENWRT_DEVICE_PRODUCT="%P"
+OPENWRT_DEVICE_REVISION="%h"
+OPENWRT_RELEASE="%D %V %C"
+OPENWRT_BUILD_DATE="%B"
diff --git a/package/base-files/files/usr/libexec/login.sh b/package/base-files/files/usr/libexec/login.sh
new file mode 100755
index 0000000..e2f898e
--- /dev/null
+++ b/package/base-files/files/usr/libexec/login.sh
@@ -0,0 +1,17 @@
+#!/bin/sh
+
+[ -t 0 ] && {
+	tty_dev=$(readlink /proc/self/fd/0)
+	case "$tty_dev" in
+		/dev/console|/dev/tty[0-9]*)
+			export TERM=${TERM:-linux}
+			;;
+		/dev/*)
+			export TERM=vt102
+			;;
+	esac
+}
+
+[ "$(uci -q get system.@system[0].ttylogin)" = 1 ] || exec /bin/login -f root
+
+exec /bin/login
diff --git a/package/base-files/files/usr/libexec/validate_firmware_image b/package/base-files/files/usr/libexec/validate_firmware_image
new file mode 100755
index 0000000..f85fb9e
--- /dev/null
+++ b/package/base-files/files/usr/libexec/validate_firmware_image
@@ -0,0 +1,66 @@
+#!/bin/sh
+
+. /lib/functions.sh
+. /lib/functions/system.sh
+. /usr/share/libubox/jshn.sh
+
+include /lib/upgrade
+
+VALID=1
+FORCEABLE=1
+ALLOW_BACKUP=1
+
+# Mark image as invalid but still possible to install
+notify_firmware_invalid() {
+	VALID=0
+}
+
+# Mark image as broken (impossible to install)
+notify_firmware_broken() {
+	VALID=0
+	FORCEABLE=0
+}
+
+# Mark image as incompatible with preserving a backup
+notify_firmware_no_backup() {
+	ALLOW_BACKUP=0
+}
+
+# Add result of validation test
+notify_firmware_test_result() {
+	local old_ns
+
+	json_set_namespace validate_firmware_image old_ns
+	json_add_boolean "$1" "$2"
+	json_set_namespace $old_ns
+}
+
+err_to_bool() {
+	[ "$1" -ne 0 ] && echo 0 || echo 1
+}
+
+fwtool_check_signature "$1" >&2
+FWTOOL_SIGNATURE=$?
+[ "$FWTOOL_SIGNATURE" -ne 0 ] && notify_firmware_invalid
+
+fwtool_check_image "$1" >&2
+FWTOOL_DEVICE_MATCH=$?
+[ "$FWTOOL_DEVICE_MATCH" -ne 0 ] && notify_firmware_invalid
+
+json_set_namespace validate_firmware_image old_ns
+json_init
+	json_add_object "tests"
+		json_add_boolean fwtool_signature "$(err_to_bool $FWTOOL_SIGNATURE)"
+		json_add_boolean fwtool_device_match "$(err_to_bool $FWTOOL_DEVICE_MATCH)"
+
+		# Call platform_check_image() here so it can add its test
+		# results and still mark image properly.
+		json_set_namespace $old_ns
+		platform_check_image "$1" >&2 || notify_firmware_invalid
+		json_set_namespace validate_firmware_image old_ns
+	json_close_object
+	json_add_boolean valid "$VALID"
+	json_add_boolean forceable "$FORCEABLE"
+	json_add_boolean allow_backup "$ALLOW_BACKUP"
+json_dump -i
+json_set_namespace $old_ns