#!/bin/ash

PROGRAM="Fibocom"

lockfile=/tmp/cellscanlock

# 检查是否存在 /tmp/celltime 文件，以及文件中的时间戳
if [ -e /tmp/celltime ]; then
    celltime=$(cat /tmp/celltime)
    current_time=$(date +%s)
    time_difference=$((current_time - celltime))
    
    # 如果时间差小于20秒，则直接退出脚本
    if [ $time_difference -lt 60 ]; then
        echo "时间间隔小于20秒，使用缓存结果"
        exit 0
    fi
fi

if [ -e ${lockfile} ]; then
    if kill -9 $(cat ${lockfile}); then
        echo "Cell scanning is already Kill it."
        rm -f ${lockfile}
    else
        echo "Removing stale lock file."
        rm -f ${lockfile}
    fi
fi

echo $$ >${lockfile}
pid=$(cat ${lockfile})
>/tmp/cellinfo
>/tmp/tmpcellinfo
echo "开始基站扫描..."
# 获取当前时间的时间戳
timestamp=$(date +%s)
echo $timestamp > /tmp/celltime
# echo -e 'at+GTCELLSCAN\r\n' >/dev/ttyUSB2
sendat 2 'AT+GTCELLSCAN'

timeout 120s cat /dev/ttyUSB2 | while read line; do
    case "$line" in "+GTCELLSCAN"*)
        echo "$line" >> /tmp/tmpcellinfo
        ;;
    esac
    case "$line" in *"OK"*)
        echo "<br>基站扫描完成"
        # 格式化输出基站信息供用户选择
        # awk '{print NR, $0}' /tmp/cellinfo
        # rm -f ${lockfile}
        # kill -9 $pid
        exit 0
        ;;
    esac
done
while read line; do
    case "$line" in "+GTCELLSCAN"*)
        operatorCode=$(echo $line | awk -F ',' '{print $2$3}')
        case "$operatorCode" in
        "46000" | "46002" | "46004" | "46007" | "46008" | "46020")
            operator="中国移动"
            ;;
        "46001" | "46006" | "46009")
            operator="中国联通"
            ;;
        "46003" | "46005" | "46011")
            operator="中国电信"
            ;;
        "46015")
            operator="中国广电"
            ;;
        *)
            operator="未知运营商"
            ;;
        esac
        earfcn=$(echo "$line" | awk -F ',' '{print $4}')
	    first_field=$(echo "$line" | awk -F ',' '{print $1}')
	    if [ "$first_field" = "+GTCELLSCAN: 4" ]; then
            lte="LTE"
            frequency_band="BAND$(echo $line | awk -F ',' '{print $10}')"
        elif [ "$first_field" = "+GTCELLSCAN: 5" ]; then
            lte="5G"
            frequency_band="N$(echo $line | awk -F ',' '{print $10}')"
        fi
	
        # frequency_band=$(earfcn_to_band $earfcn)
        echo "$line" | awk -F ',' -v lte="$lte" -v operator="$operator" -v frequency_band="$frequency_band" -v earfcn="$earfcn" '{printf("%s,%s,%s,%s,%s,%s,%s,%s\n", lte, operator, frequency_band, earfcn, $5, $8, $9, $7)}' >> /tmp/cellinfo
        ;;
    esac
done < /tmp/tmpcellinfo
echo "<br>数据处理完成"
rm -f ${lockfile}
# 获取当前时间的时间戳
timestamp=$(date +%s)
echo $timestamp > /tmp/celltime

rm -f ${lockfile}