#!/bin/sh /etc/rc.common

START=80

copy_certificates() {
	[ -f /certificates/dev-id ] || return

	cp /certificates/*.pem /etc/ucentral/
	cp /certificates/dev-id /etc/ucentral/
	chown root.network /etc/ucentral/*.pem
	chmod 0440 root.network /etc/ucentral/*.pem
	chmod 0400 /etc/ucentral/dev-id
	[ -f /certificates/restrictions.json ] && cp /certificates/restrictions.json /etc/ucentral/
	exit 0
}

boot() {
	[ -f /etc/ucentral/dev-id ] && return
	. /lib/functions.sh
	mkdir -p /certificates /etc/ucentral/
	local mtd=$(find_mtd_index certificates)
	
	if [ "$(head -c 4 /dev/mtd$mtd)" == "hsqs" ]; then
		mount -t squashfs /dev/mtdblock$mtd /certificates
	else
		[ -n "$mtd" -a -f /sys/class/mtd/mtd$mtd/oobsize ] && ubiattach -p /dev/mtd$mtd
		if [ -n "$(ubinfo -a | grep certificates)" ]; then
			[ -e /dev/ubi0 ] && mount -t ubifs ubi0:certificates /certificates
			[ -e /dev/ubi1 ] && mount -t ubifs ubi1:certificates /certificates
		fi
	fi
	copy_certificates

	# if we get here no valid certificates were found

	. /lib/functions.sh

	local PART_NAME

	case "$(board_name)" in
	actiontec,web7200)
		if grep -q bootselect=0 /proc/cmdline; then
			PART_NAME=firmware2
		else
			PART_NAME=firmware1
		fi
		;;
	edgecore,ecw5211|\
	edgecore,eap101|\
	edgecore,eap102)
		if grep -q rootfs1 /proc/cmdline; then
			PART_NAME=rootfs2
		else
			PART_NAME=rootfs1
		fi	
		;;
	hfcl,ion4xi|\
	hfcl,ion4xe)
		if grep -q rootfs_1 /proc/cmdline; then
			PART_NAME=rootfs
		else
			PART_NAME=rootfs_1
		fi	
		;;
	*)
		return 1
		;;
	esac

	local MTD=$(find_mtd_index $PART_NAME)

	[ -z "$MTD" ] && return 1

	ubiattach -m $MTD -d 3
	[ -e /dev/ubi3 ] && mount -t ubifs ubi3:certificates /certificates
	copy_certificates
}
