#include <stdio.h>
#include <stdlib.h>

#define REPO_ROOT "/Users/mrjunejune/zenbu"

#include <stdint.h>
#include <arpa/inet.h>

void run_hg_command(FILE *hg_pipe) {
    char channel;
    uint32_t net_len;
    
    while (fread(&channel, 1, 1, hg_pipe) == 1) {
        // 1. Read the 4-byte length
        fread(&net_len, 4, 1, hg_pipe);
        uint32_t length = ntohl(net_len);

        // 2. If it's an 'o' (output), it's the data you want
        if (channel == 'o' || channel == 'e') {
            char *buf = malloc(length + 1);
            fread(buf, 1, length, hg_pipe);
            buf[length] = '\0';
            printf("%s", buf); // This is your capability string
            free(buf);
        } 
        // 3. IF THE CHANNEL IS 'r', THE COMMAND IS DONE. STOP HERE.
        else if (channel == 'r') {
            int32_t result;
            // The 'r' channel payload is the 4-byte return code
            fread(&result, 4, 1, hg_pipe); 
            printf("\nCommand finished with result: %d\n", ntohl(result));
            break; // <--- THIS IS YOUR EXIT
        }
    }
}

int main()
{
  char command[512];
  snprintf(command, sizeof(command), "hg -R %s serve --stdio", REPO_ROOT);
  printf("command: %s\n", command);
  
  FILE *hg_pipe = popen(command, "r+");
  if (!hg_pipe)
  {
    printf("Failed to open pipe\n");
    return -1;
  }

  fprintf(hg_pipe, "capabilities\n");
  fflush(hg_pipe);

  run_hg_command(hg_pipe);
  // char *output = malloc(sizeof(char) * 2048);
  // char *curr = output;
  // int c;
  // int number_of_breakline = 0;
  // while ((c = fgetc(hg_pipe))  != NULL)
  // {
  //   *curr++ = c;
  //   printf("output: %s\n", output);
  //   if (c == '\n')
  //     number_of_breakline++;
  //   if (number_of_breakline == 2)
  //     break;
  //   printf("char: %c\n", c);
  // }
  pclose(hg_pipe);


  return 0;
}


