#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/route.h>
#include "cJSON.h"
#include "dy_common.h"
#include "../common.h"

#define RTABLE_SIZE 1024
#define LOCATION_4G_ICCIC_PATH "/tmp/.modem_4ginfo.json"
#define LOCATION_VAILD_ICCIC_PATH "/tmp/simcard_iccid"
#define LOCALTION_4G_SIGN_PATH    "/etc/signal_4g.txt"

int get_network_type() // 返回值: 0 - 有线上网, 1 - 4G上网, -1 - 无法确定
{
    FILE* fp;
    char  line[256];
    char  interface[32] = {0};
    fp = popen("ip route show default | awk '/default/ {print $5}'", "r");
    if (fp == NULL)
    {
        return -1;
    }

    if (fgets(line, sizeof(line), fp) != NULL)
    {
        line[strcspn(line, "\n")] = 0;
        strncpy(interface, line, sizeof(interface) - 1);
    }
    pclose(fp);
    if (strlen(interface) == 0)
    {
        return -1;
    }
    if (strncmp(interface, "eth", 3) == 0)
    {
        return 2;
    }
    if (strncmp(interface, "usb", 3) == 0 || strncmp(interface, "emp", 3) == 0)
    {
        return 1;
    }
    return -1;
}

int get_4g_iccid(char* dst, int max_len) {
    char* data = NULL;

    cJSON* root = NULL;
    int    ret  = 0;
    cJSON *iccid0 = NULL;
    cJSON *iccid1 = NULL;
    
    data = read_file_data(LOCATION_4G_ICCIC_PATH);

    if (data == NULL)
    {
        ems_syslog(LOG_ERR, "读取4GICCIDS文件失败, file:%s", LOCATION_4G_ICCIC_PATH);
        goto END;
    }
    root = cJSON_Parse(data);
    if (!root)
    {
        ems_syslog(LOG_ERR, "文件解析失败, file:%s", LOCATION_4G_ICCIC_PATH);
        goto END;
    }

    // 获取ICCID0和ICCID1
    iccid0 = cJSON_GetObjectItem(root, "ICCID0");
    iccid1 = cJSON_GetObjectItem(root, "ICCID1");

    if (iccid0 != NULL && iccid0->valuestring != NULL && iccid0->valuestring[0] != '\0')
    {
        ret = snprintf(dst, max_len, "%s", iccid0->valuestring);
    }

    if (iccid1 != NULL && iccid1->valuestring != NULL && iccid1->valuestring[0] != '\0')
    {
        if (ret > 0)
        {
            dst[ret] = ',';
            ret++;
        }
        ret += snprintf(dst + ret, max_len - ret, "%s", iccid1->valuestring);
    }

END:
    if (data) free(data);
    if (root) cJSON_Delete(root);
    return ret;
}

int get_vaild_4g_iccid(char* dst, int max_len)
{
    char* data = NULL;
    int   ret  = -1;

    data = read_file_data(LOCATION_VAILD_ICCIC_PATH);

    if (data == NULL || data[0] == '\0')
    {
        ems_syslog(LOG_ERR, "读取4GICCIDS文件失败, file:%s", LOCATION_4G_ICCIC_PATH);
        goto END;
    }
    char iccid[21] = {0}; // ICCID是20位数字，加上字符串结束符'\0'
    sscanf(data, "%*[^0123456789] %20s", iccid);
    ret = snprintf(dst, max_len, "%s", iccid);
END:
    if (data) free(data);
    return ret;
}

int get_4g_sign()
{
    char* data = read_file_data(LOCALTION_4G_SIGN_PATH);
    int   sign = 99;
    if (data != NULL && data[0] != '\0')
    {
        sign = atoi(data);
        free(data);
    }
    return sign;
}
