#!/bin/sh /etc/rc.common
# Example script
# Copyright (C) 2007 OpenWrt.org

START=99
STOP=90

USE_PROCD=1

start_service() {

	if [ ! -f /usr/lib/libjson-c.so ]; then
		ln /usr/lib/libjson-c.so.5 /usr/lib/libjson-c.so
	fi;

	if [ ! -f /usr/lib/libcrypto.so.1.0.0 ]; then
		ln -s /usr/lib/libcrypto.so.1.1 /usr/lib/libcrypto.so.1.0.0
	fi;

	if [ ! -f /lib/libblobmsg_json.so ];then
		ln -s /lib/libblobmsg_json.so.20210516 /lib/libblobmsg_json.so
	fi;

	if [ ! -f /lib/libubox.so ];then
		ln -s /lib/libubox.so.20210516 /lib/libubox.so
	fi;

	if [ ! -f /lib/libubus.so ];then
		ln -s /lib/libubus.so.20210630 /lib/libubus.so
	fi;

	if [ ! -f /lib/libjson_script.so ];then
		ln -s /lib/libjson_script.so.20210516 /lib/libjson_script.so
	fi;

	local mpt=`devinfo show mptdone`
	if [ -z "$mpt" ] || [ 1 -ne $mpt ]
	then
		return 0
	fi

	while [ "`ls -A /plugin`" = "" ]
	do
		echo "wait mount plugin success." > /dev/console
		sleep 1 # wait plugin mount success
	done

	readonly=`devinfo show readonly`
	if [ -z $readonly ]; then
		readonly="0"
	fi
	echo "readonly: $readonly"
	if [ "$readonly" -eq "1" ]; then
		if [ ! -d /plugin/ctc-files/ctcap ]; then
			mkdir -p /plugin/ctc-files/ctcap && cp /ctcap/* /plugin/ctc-files/ctcap
		fi
		mount --bind /plugin/ctc-files/ctcap /ctcap
		if [ ! -d /plugin/ctc-files/ipks ]; then
			mkdir -p /plugin/ctc-files/ipks && cp /ipks/* /plugin/ctc-files/ipks
		fi
		mount --bind /plugin/ctc-files/ipks /ipks 
	else
		if [ ! -d /plugin/ctc-files ]; then
			mkdir /plugin/ctc-files
			ln -snf /ipks /plugin/ctc-files/ipks
			ln -snf /ctcap /plugin/ctc-files/ctcap
		fi
	fi

	sleep 5 # wait until ubus ready
	procd_open_instance
	procd_set_param command /bin/init.ctc
	#procd_set_param limits core="unlimited"
	procd_set_param respawn
	procd_close_instance
}
reload_service() {
	rc_procd start_service 
	return 0
}
