#!/bin/sh
set -x

##判断tf卡是不是初始化成功了
check_tf() {
	status=`df | grep mmcblk0p1 | wc -l`
	if [ -e /dev/mmcblk0p1 ];then
		if [ $status == 0 ]; then
			fsck.ext4 /dev/mmcblk0p1
			mount -t ext4 /dev/mmcblk0p1 /mnt/mmcblk0p1
			date > /tmp/mountmmc0.txt
			echo "mdev:mmcblk0p1 mntpath:/mnt/mmcblk0p1" >> /tmp/mountmmc0.txt""
			return 0
		elif [ $status == 1 ];then
			return 0
		fi
		echo "tf card faid"
		return 1
	fi
	echo "tf card faid"
	return 1
}

##判断是否插入卡了，是的话才可以下载Python的包并初始化
install_python() {
	if [ -e /dev/mmcblk0p1 ] && [ -d /mnt/mmcblk0p1 ];then
		tftp -gr 7042_python.tar.gz -l /mnt/mmcblk0p1/7042_python.tar.gz $1
		cd /mnt/mmcblk0p1/ && tar -zxf /mnt/mmcblk0p1/7042_python.tar.gz && rm -rf /mnt/mmcblk0p1/7042_python.tar.gz
		/usr/sbin/pysdk_recover
		return 0
	fi
	return 1
}

##检查是否安装成功
check_installation() {
    # 定义软连接和需要检查的命令
    PYTHON_LINK="/usr/python"
    PYUSER_LINK="/usr/pyuser"

    # 检查 /usr/python 是否存在并是软链接
    if [ -L "$PYTHON_LINK" ]; then
        PYTHON_TARGET=$(readlink -f "$PYTHON_LINK")
        if [ -d "$PYTHON_TARGET" ]; then
            echo "软链接 $PYTHON_LINK 存在，指向目录: $PYTHON_TARGET"
        else
            echo "软链接 $PYTHON_LINK 指向的目录 $PYTHON_TARGET 不存在！"
            return 1
        fi
    else
        echo "软链接 $PYTHON_LINK 不存在！"
        return 1
    fi

    # 检查 /usr/pyuser 是否存在并是软链接
    if [ -L "$PYUSER_LINK" ]; then
        PYUSER_TARGET=$(readlink -f "$PYUSER_LINK")
        if [ -d "$PYUSER_TARGET" ]; then
            echo "软链接 $PYUSER_LINK 存在，指向目录: $PYUSER_TARGET"
        else
            echo "软链接 $PYUSER_LINK 指向的目录 $PYUSER_TARGET 不存在！"
            return 1
        fi
    else
        echo "软链接 $PYUSER_LINK 不存在！"
        return 1
    fi

    # 检查 python 是否可以执行
    if command -v python >/dev/null 2>&1; then
        PYTHON_VERSION=$(python -V 2>&1)
        echo "Python 可以执行，版本为: $PYTHON_VERSION"
    else
        echo "Python fail，未找到 'python' 命令！"
        return 1
    fi

    echo "所有检查通过，系统安装正常。"
    return 0
}

start_python_app() {
	ubus call yruo_python set '{"base":"appmanager","index":1,"value":{"enable":1}}'
	ubus call yruo_apply apply '{}'
}

check_tf
ret=$?
if [ $ret == 0 ];then
	check_installation
	ret=$?
	if [ $ret == 1 ];then
		install_python $1 && check_installation && start_python_app
	fi
fi 