#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <cJSON.h>
#include "tailscale_deploy.h"
#include "common.h"

int tailscale_control(cJSON *body) {
    if (body == NULL) {
        my_zlog_error("tailscale_control: body is NULL");
        return -1;
    }

    cJSON *authkey_json = cJSON_GetObjectItem(body, "authkey");
    if (!cJSON_IsString(authkey_json) || (authkey_json->valuestring == NULL)) {
        my_zlog_error("tailscale_control: authkey is missing or invalid");
        return -2;
    }

    char *authkey = authkey_json->valuestring;

    if (strcmp(authkey, "stop") == 0) {
        my_zlog_info("tailscale_control: Stopping Tailscale...");
        // 尝试停止 tailscale并捕获输出
        FILE *fp = popen("sudo tailscale down 2>&1", "r");
        if (fp != NULL) {
            char buf[256];
            while (fgets(buf, sizeof(buf), fp) != NULL) {
                // 去除换行符让日志更整洁
                size_t len = strlen(buf);
                if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
                my_zlog_info("tailscale output: %s", buf);
            }
            int ret = pclose(fp);
            if (WEXITSTATUS(ret) == 0) {
                 my_zlog_info("tailscale_control: Tailscale stopped successfully");
            } else {
                 my_zlog_warn("tailscale_control: Failed to stop Tailscale, ret=%d", WEXITSTATUS(ret));
                 return -3;
            }
        } else {
             my_zlog_error("tailscale_control: Failed to execute stop command");
             return -3;
        }

    } else {
        // 检查 tailscale 是否安装
        if (system("which tailscale > /dev/null 2>&1") != 0) {
            my_zlog_info("tailscale_control: Tailscale not found. Installing...");
            // 安装 tailscale
            int install_ret = system("curl -fsSL https://tailscale.com/install.sh | sh");
            if (install_ret != 0) {
                my_zlog_warn("tailscale_control: Failed to install Tailscale, ret=%d", install_ret);
                return -4;
            }
            // 用户要求不开机自启，因此先 disable
            int disable_ret = system("sudo systemctl disable tailscaled > /dev/null 2>&1");
            if (disable_ret != 0) {
                my_zlog_warn("tailscale_control: disable tailscaled failed, ret=%d", disable_ret);
            }
            my_zlog_info("tailscale_control: Tailscale installed successfully");
        }

        // 确保服务已启动
        int start_service_ret = system("sudo systemctl start tailscaled > /dev/null 2>&1");
        if (start_service_ret != 0) {
            my_zlog_warn("tailscale_control: start tailscaled service failed, ret=%d", start_service_ret);
        }

        // 启动 tailscale
        char cmd[512];
        snprintf(cmd, sizeof(cmd), "sudo tailscale up --authkey %s --hostname orangepi-01 2>&1", authkey);
        
        my_zlog_info("tailscale_control: Starting Tailscale...");
        
        FILE *fp_up = popen(cmd, "r");
        if (fp_up != NULL) {
             char buf[256];
             while (fgets(buf, sizeof(buf), fp_up) != NULL) {
                size_t len = strlen(buf);
                if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
                my_zlog_info("tailscale up output: %s", buf);
             }
             int start_ret = pclose(fp_up);
             if (WEXITSTATUS(start_ret) == 0) {
                my_zlog_info("tailscale_control: Tailscale started successfully");
             } else {
                my_zlog_warn("tailscale_control: Failed to start Tailscale, ret=%d", WEXITSTATUS(start_ret));
                return -5;
             }
        } else {
             my_zlog_error("tailscale_control: Failed to execute start command");
             return -5;
        }
    }

    return 0;
}
