#!/bin/sh /etc/rc.common
#
# Copyright (c) 2013, 2017, 2020 Qualcomm Technologies, Inc.
#
# All Rights Reserved.
# Confidential and Proprietary - Qualcomm Technologies, Inc.
#
# 2013 Qualcomm Atheros, Inc.
#
# All Rights Reserved.
# Qualcomm Atheros Confidential and Proprietary
#

. /lib/functions.sh
[ -e /lib/ipq806x.sh ] && . /lib/ipq806x.sh

START=97
SERVICE_DAEMONIZE=1
SERVICE_WRITE_PID=1

MTD_ART_PART_NAME="art"

compressed_art_read() {
	local mtdblock=$(find_mtd_part 0:ART)

	if [ -z "$mtdblock" ]; then
		#read from mmc
		mtdblock=$(find_mmc_part 0:ART)
	fi

	[ -n "$mtdblock" ] || return

	local apmp="/tmp"

	dd if=${mtdblock} of=${apmp}/virtual_art.bin.lzma
	lzma -fdv --single-stream ${apmp}/virtual_art.bin.lzma || {
	# Create dummy virtual_art.bin file of size 512K
	dd if=/dev/zero of=${apmp}/virtual_art.bin bs=1024 count=512
	}
	echo "Uncompressed and Copied ART content from ${mtdblock} to /tmp/virtual_art.bin" > /dev/console
}

raw_art_read() {
	local mtdblock=$(find_mtd_part 0:ART)

	if [ -z "$mtdblock" ]; then
		#read from mmc
		mtdblock=$(find_mmc_part 0:ART)
	fi

	[ -n "$mtdblock" ] || return

	local apmp="/tmp"

	dd if=${mtdblock} of=${apmp}/virtual_art.bin
	echo "Copy ART caldata from ${mtdblock} to /tmp/virtual_art.bin" > /dev/console
}

retrieve_caldata() {
	local board
	[ -f /tmp/sysinfo/board_name ] && {
		board=ap$(cat /tmp/sysinfo/board_name | awk -F 'ap' '{print$2}')
	}
	echo "**** Platform Name: $board *****" > /dev/console

	if [ -e /sys/firmware/devicetree/base/compressed_art ]
	then
		compressed_art_read
	else
		raw_art_read
	fi
}

start() {
	local emmc_flash=""
	local nor_flash=""

	emmc_flash=$(find_mmc_part 0:ART 2> /dev/null)
	mtd_name=$(grep -i -w ${MTD_ART_PART_NAME} /proc/mtd | cut -f1 -d:)
	nor_flash=`find /sys/bus/spi/devices/*/mtd -name ${mtd_name} 2> /dev/null`

	if [ -n "$emmc_flash" ]; then
		[ -L /dev/caldata ] || \
			ln -s $emmc_flash /dev/caldata
	elif [ -n "$nor_flash" ]; then
		[ -L /dev/caldata ] || \
			ln -s /dev/${mtd_name//mtd/mtdblock} /dev/caldata
	elif [ -n "$mtd_name" ]; then
		[ -L /dev/caldata ] || \
			ln -s /dev/${mtd_name//mtd/mtdblock} /dev/caldata
	fi
	retrieve_caldata
}

stop() {
	[ -L /dev/caldata ] && rm /dev/caldata
}
