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

int main(int argc, char *argv[]) {
    if ((argc != 3 && argc != 6) || (argc == 6 && strcmp(argv[3], "-ssh") != 0)) {
        fprintf(stderr, "Usage: %s <source_folder> <target_folder> [-ssh <ssh_username> <ssh_hostname>]\n", argv[0]);
        return EXIT_FAILURE;
    }

    const char *source_folder = argv[1];
    const char *target_folder = argv[2];

    char command[1024]; // Adjust buffer size accordingly

    if (argc == 6) {
        // Sync to a remote target folder over SSH
        const char *ssh_username = argv[4];
        const char *ssh_hostname = argv[5];
        
        // Build the fswatch command
        snprintf(command, sizeof(command), "fswatch -r \"%s\" | while read -r; do rsync -av --delete -e 'ssh' \"%s/\" \"%s@%s:%s\"; done", source_folder, source_folder, ssh_username, ssh_hostname, target_folder);
    } else {
        // Sync to a local target folder
        // Build the fswatch command
        snprintf(command, sizeof(command), "fswatch -r \"%s\" | while read -r; do rsync -av --delete \"%s/\" \"%s\"; done", source_folder, source_folder, target_folder);
    }

    // Execute the fswatch command
    FILE *fp = popen(command, "r");
    if (fp == NULL) {
        perror("popen");
        return EXIT_FAILURE;
    }

    // Keep the program running
    while (1) {
        sleep(1); // Or do other processing here if needed
    }

    // Close the file pointer
    pclose(fp);

    return EXIT_SUCCESS;
}
