aboutsummaryrefslogtreecommitdiff
path: root/src/main.c
blob: fa4ca205abe87f65373043739cb4e1fd94b9b5ee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
#include "buffer.h"
#include "fileutils.h"
#include "transmission.h"
#include "fileutils.h"
#include "stringutils.h"
#include "program.h"
#include "rss.h"
#include "rss_html_common.h"
#include "html.h"
#include "track_remove_parser.h"
#include "../depends/cJSON.h"
#include "alloc.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <locale.h>
#include <time.h>
#include <assert.h>

#include <dirent.h>
#include <libgen.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>

#define NAME_MAX_LEN 250
/* 30 minutes */
#define IN_PROGRESS_TIMEOUT_SEC 60L*30L

static void usage(void) {
    fprintf(stderr, "usage: automedia COMMAND\n");
    fprintf(stderr, "\n");
    fprintf(stderr, "COMMANDS\n");
    fprintf(stderr, "  add           Add media to track\n");
    fprintf(stderr, "  sync          Start syncing tracked media\n");
    fprintf(stderr, "  downloaded    List downloaded media\n");
    fprintf(stderr, "  cleanup       Stop tracking media that has stopped getting updates (either finished or dropped media)\n");
    exit(1);
}

static void usage_add(void) {
    fprintf(stderr, "usage: automedia add <type> <url|filename> [--name name] [--start-after start_after]\n");
    fprintf(stderr, "OPTIONS\n");
    fprintf(stderr, "  type             The type should be either rss or html\n");
    fprintf(stderr, "  url              The url to the rss or html\n");
    fprintf(stderr, "  filename         The filename of an episode of an existing serie to start track. Currently only works with rss on https://nyaa.si\n");
    fprintf(stderr, "  --name           The display name to be used for the media. Optional for rss, in which case the name will be the rss TITLE, required for html. The name can't be longer than 250 characters\n");
    fprintf(stderr, "  --start-after    The sync should start downloading media after this item. This --start-after value should be the title of the episode/chapter (Optional, default is to start from the first item)\n");
    fprintf(stderr, "EXAMPLES\n");
    fprintf(stderr, "  automedia add rss 'https://nyaa.si/?page=rss&q=Tejina-senpai+1080p&c=0_0&f=0&u=HorribleSubs'\n");
    fprintf(stderr, "  automedia add html 'https://manganelo.com/manga/read_naruto_manga_online_free3' --name Naruto\n");
    fprintf(stderr, "  automedia add rss '[Erai-raws] Saiki Kusuo no Psi Nan - Kanketsu-hen - 01 [1080p][Multiple Subtitle].mkv'\n");
    exit(1);
}

static void usage_sync(void) {
    fprintf(stderr, "usage: automedia sync <download_dir>\n");
    fprintf(stderr, "OPTIONS\n");
    fprintf(stderr, "  download_dir    The path where media should be downloaded to\n");
    fprintf(stderr, "EXAMPLES\n");
    fprintf(stderr, "  automedia sync /home/adam/Downloads/automedia\n");
    exit(1);
}

static void usage_cleanup(void) {
    fprintf(stderr, "usage: automedia cleanup <days>\n");
    fprintf(stderr, "OPTIONS\n");
    fprintf(stderr, "  days    Media that haven't received any updates in the specified amount of days are removed\n");
    fprintf(stderr, "EXAMPLES\n");
    fprintf(stderr, "  automedia cleanup 100\n");
    exit(1);
}

typedef void (*DownloadedListCallback)(const char *title, double timestamp, void *userdata);

static void data_file_get_downloaded(const char *dir_name, const char *data_filepath, int is_html, DownloadedListCallback callback, void *userdata) {
    char *file_data;
    long file_size;
    if(file_get_content(data_filepath, &file_data, &file_size) != 0) {
        fprintf(stderr, "Failed to read the content of file %s\n", data_filepath);
        return;
    }

    cJSON *json_root = cJSON_ParseWithLength(file_data, file_size);
    if(!json_root) {
        fprintf(stderr, "Failed to parse file %s as json\n", data_filepath);
        goto cleanup;
    }
    free(file_data);
    file_data = NULL;

    if(!cJSON_IsObject(json_root)) {
        fprintf(stderr, "File %s contains malformed json. Expected json root element to be an object\n", data_filepath);
        goto cleanup;
    }

    const cJSON *downloaded_json = cJSON_GetObjectItemCaseSensitive(json_root, "downloaded");
    if(!downloaded_json) {
        fprintf(stderr, "File %s contains malformed json. Expected json to contain \"downloaded\"\n", data_filepath);
        goto cleanup;
    }

    if(!cJSON_IsArray(downloaded_json)) {
        fprintf(stderr, "File %s contains malformed json. Expected \"downloaded\" to be an array\n", data_filepath);
        goto cleanup;
    }

    const cJSON *downloaded_item_json = NULL;
    cJSON_ArrayForEach(downloaded_item_json, downloaded_json) {
        if(!cJSON_IsObject(downloaded_item_json))
            continue;

        const cJSON *filler_json = cJSON_GetObjectItemCaseSensitive(downloaded_item_json, "filler");
        if(cJSON_IsTrue(filler_json))
            continue;

        const cJSON *time_json = cJSON_GetObjectItemCaseSensitive(downloaded_item_json, "time");
        if(!time_json || !cJSON_IsString(time_json))
            continue;
        
        const cJSON *title_json = cJSON_GetObjectItemCaseSensitive(downloaded_item_json, "title");
        const cJSON *filename_json = cJSON_GetObjectItemCaseSensitive(downloaded_item_json, "filename");

        /* Filename limit is 256, so this should be safe... */
        char title[256];
        if(filename_json && cJSON_IsString(filename_json)) {
            strcpy(title, filename_json->valuestring);
        } else if(title_json && cJSON_IsString(title_json)) {
            if(is_html) {
                snprintf(title, sizeof(title), "%s/%s", dir_name, title_json->valuestring);
            } else {
                strcpy(title, title_json->valuestring);
            }
        } else {
            continue;
        }

        callback(title, atof(time_json->valuestring), userdata);
    }

    cleanup:
    cJSON_Delete(json_root);
    free(file_data);
}

typedef struct {
    char *title;
    double timestamp;
} DownloadedListData;

static void downloaded_list_callback(const char *title, double timestamp, void *userdata) {
    DownloadedListData list_data;
    list_data.title = strdup(title);
    list_data.timestamp = timestamp;

    Buffer *buffer = userdata;
    buffer_append(buffer, &list_data, sizeof(list_data));
}

static void get_downloaded_items(const char *tracked_dir, int is_html, void *userdata) {
    struct dirent *dir;
    DIR *d = opendir(tracked_dir);
    if(!d) {
        fprintf(stderr, "Failed to open directory: %s\n", tracked_dir);
        return;
    }

    char data_filepath[PATH_MAX];
    strcpy(data_filepath, tracked_dir);
    strcat(data_filepath, "/");
    int data_filepath_length = strlen(data_filepath);

    while((dir = readdir(d)) != NULL) {
        int filename_len = strlen(dir->d_name);
        if((filename_len == 1 && dir->d_name[0] == '.') || (filename_len == 2 && dir->d_name[0] == '.' && dir->d_name[1] == '.'))
            continue;

        strcpy(data_filepath + data_filepath_length, dir->d_name);
        strcpy(data_filepath + data_filepath_length + filename_len, "/data");
        data_file_get_downloaded(dir->d_name, data_filepath, is_html, downloaded_list_callback, userdata);
    }

    closedir(d);
}

static int compare_downloaded_item(const void *a, const void *b) {
    const DownloadedListData *list_data_a = a;
    const DownloadedListData *list_data_b = b;
    return list_data_a->timestamp - list_data_b->timestamp;
}

typedef struct {
    char *item_tracked_path;
    time_t updated_time;
} TrackedItemData;

static void get_tracked_items(const char *tracked_dir, time_t age_sec, Buffer /*TrackedItemData*/ *tracked_items_buffer) {
    struct dirent *dir;
    DIR *d = opendir(tracked_dir);
    if(!d) {
        fprintf(stderr, "Failed to open directory: %s\n", tracked_dir);
        return;
    }

    char data_filepath[PATH_MAX];
    strcpy(data_filepath, tracked_dir);
    strcat(data_filepath, "/");
    int data_filepath_length = strlen(data_filepath);

    time_t time_now = time(NULL);
    char *file_data;
    long file_size;

    while((dir = readdir(d)) != NULL) {
        int filename_len = strlen(dir->d_name);
        if((filename_len == 1 && dir->d_name[0] == '.') || (filename_len == 2 && dir->d_name[0] == '.' && dir->d_name[1] == '.'))
            continue;

        strcpy(data_filepath + data_filepath_length, dir->d_name);

        strcpy(data_filepath + data_filepath_length + filename_len, "/updated");
        if(file_get_content(data_filepath, &file_data, &file_size) != 0) {
            fprintf(stderr, "Failed to read the content of file %s\n", data_filepath);
            continue;
        }

        time_t updated_time = 0;
        sscanf(file_data, "%ld", &updated_time);
        free(file_data);
        if(time_now - updated_time <= age_sec)
            continue;

        char *p = alloc_or_crash(data_filepath_length + filename_len + 1);
        memcpy(p, data_filepath, data_filepath_length);
        memcpy(p + data_filepath_length, dir->d_name, filename_len);
        p[data_filepath_length + filename_len] = '\0';

        TrackedItemData tracked_item_data;
        tracked_item_data.item_tracked_path = p;
        tracked_item_data.updated_time = updated_time;
        buffer_append(tracked_items_buffer, &tracked_item_data, sizeof(tracked_item_data));
    }

    closedir(d);
}

static void command_add(int argc, char **argv, char *rss_config_dir, char *html_config_dir, char *program_dir) {
    if(argc < 2)
        usage_add();
    
    char *media_type = argv[0];
    char *media_url = argv[1];
    char *media_name = NULL;
    char *start_after = NULL;

    const char *option = NULL;
    for(int i = 2; i < argc; ++i) {
        char *arg = argv[i];
        if(strcmp(arg, "--name") == 0 || strcmp(arg, "--start-after") == 0) {
            if(option)
                usage_add();
            option = arg;
        } else {
            if(!option)
                usage_add();
            
            if(strcmp(option, "--name") == 0)
                media_name = arg;
            else if(strcmp(option, "--start-after") == 0)
                start_after = arg;
            else {
                fprintf(stderr, "Invalid option %s\n", option);
                usage_add();
            }

            option = NULL;
        }
    }

    if(media_name) {
        string_replace(media_name, '/', '_');
        media_name = strip(media_name);

        int media_name_len = strlen(media_name);
        if(media_name_len > NAME_MAX_LEN) {
            fprintf(stderr, "--name value can't be longer than %d characters\n", NAME_MAX_LEN);
            exit(1);
        }

        if(strcmp(media_name, ".") == 0 || strcmp(media_name, "..") == 0) {
            fprintf(stderr, "--name can't be . or ..\n");
            exit(1);
        }
    }

    if(start_after) {
        string_replace(start_after, '/', '_');
        start_after = strip(start_after);
    }

    media_url = strip(media_url);

    if(strcmp(media_type, "rss") == 0) {
        int res = create_directory_recursive(rss_config_dir);
        if(res != 0) {
            fprintf(stderr, "Failed to create %s, error: %s\n", rss_config_dir, strerror(res));
            exit(1);
        }

        if(add_rss(media_name, media_url, rss_config_dir, start_after) != 0)
            exit(1);
    } else if(strcmp(media_type, "html") == 0) {
        int res = create_directory_recursive(html_config_dir);
        if(res != 0) {
            fprintf(stderr, "Failed to create %s, error: %s\n", html_config_dir, strerror(res));
            exit(1);
        }

        if(add_html(media_name, media_url, html_config_dir, program_dir, start_after) != 0)
            exit(1);
    } else {
        fprintf(stderr, "type should be either rss or html\n");
        usage_add();
    }
}

sig_atomic_t automedia_running = 0;
static void automedia_pid_signal_handler(int signum) {
    (void)signum;
    automedia_running = 0;
}

int is_program_running() {
    return automedia_running;
}

/* plugin is NULL for rss */
typedef int (*IterateTrackedItemCallback)(char *title, char *link, char *plugin, char *config_dir, cJSON *json_data, void *userdata);
static void iterate_tracked_items(char *config_dir, IterateTrackedItemCallback iterate_callback, void *userdata) {
    /*
        TODO: Only iterate updated items. To make that work, sync_rss and sync_html need to be updated to update
        the json_object with new downloaded items (and not only temporary downloaded items) and then also only
        clean them up!
    */

    char tracked_dir[PATH_MAX];
    strcpy(tracked_dir, config_dir);
    strcat(tracked_dir, "/tracked");

    struct dirent *dir;
    DIR *d = opendir(tracked_dir);
    if(!d) {
        fprintf(stderr, "Failed to open directory: %s\n", tracked_dir);
        return;
    }

    char *item_filepath = tracked_dir;
    strcat(item_filepath, "/");
    int item_filepath_len = strlen(item_filepath);

    time_t time_now = time(NULL);

    while((dir = readdir(d)) != NULL && automedia_running) {
        int title_len = strlen(dir->d_name);
        if((title_len == 1 && dir->d_name[0] == '.') || (title_len == 2 && dir->d_name[0] == '.' && dir->d_name[1] == '.'))
            continue;

        strcpy(item_filepath + item_filepath_len, dir->d_name);

        strcpy(item_filepath + item_filepath_len + title_len, "/.in_progress");
        time_t last_modified = 0;
        if(file_get_last_modified_time(item_filepath, &last_modified) == 0) {
            if(time_now - last_modified > IN_PROGRESS_TIMEOUT_SEC) {
                fprintf(stderr, "Removing in-progress item: %s\n", dir->d_name);
                remove(item_filepath);
            } else {
                fprintf(stderr, "Skipping in-progress item: %s\n", dir->d_name);
                continue;
            }
        }

        char *link_file_content = NULL;
        char *data_file_content = NULL;
        char *plugin_file_content = NULL;
        cJSON *json_data = NULL;

        strcpy(item_filepath + item_filepath_len + title_len, "/link");
        long link_file_size = 0;
        int has_link = file_get_content(item_filepath, &link_file_content, &link_file_size);

        strcpy(item_filepath + item_filepath_len + title_len, "/data");
        long data_file_size = 0;
        int has_data = file_get_content(item_filepath, &data_file_content, &data_file_size);

        strcpy(item_filepath + item_filepath_len + title_len, "/plugin");
        long plugin_file_size = 0;
        file_get_content(item_filepath, &plugin_file_content, &plugin_file_size);

        if(has_link != 0 || has_data != 0) {
            fprintf(stderr, "Rss corrupt, link or data missing for rss %s\n", dir->d_name);
            goto cleanup_item;
        }

        json_data = cJSON_ParseWithLength(data_file_content, data_file_size);
        if(!json_data || !cJSON_IsObject(json_data)) {
            fprintf(stderr, "Rss corrupt for %s\n", dir->d_name);
            goto cleanup_item;
        }
        free(data_file_content);
        data_file_content = NULL;
        
        if(iterate_callback(dir->d_name, link_file_content, plugin_file_content, config_dir, json_data, userdata) != 0)
            fprintf(stderr, "Failed to sync %s\n", dir->d_name);

        cleanup_item:
        cJSON_Delete(json_data);
        free(plugin_file_content);
        free(data_file_content);
        free(link_file_content);
    }

    closedir(d);
}

static int iterate_tracked_item_rss_callback(char *title, char *link, char *plugin, char *config_dir, cJSON *json_data, void *userdata) {
    (void)plugin;
    TransmissionSession *transmission_session = userdata;
    TrackedRss tracked_rss;
    tracked_rss.title = title;
    tracked_rss.link = link;
    tracked_rss.json_data = json_data;
    return sync_rss(&tracked_rss, transmission_session, config_dir);
}

typedef struct {
    char *program_dir;
    const char *download_dir;
} IterateHtmlItemUserdata;

static int iterate_tracked_item_html_callback(char *title, char *link, char *plugin, char *config_dir, cJSON *json_data, void *userdata) {
    if(!plugin) {
        fprintf(stderr, "Missing plugin name for html item: %s\n", title);
        return -1;
    }

    IterateHtmlItemUserdata *iterate_html_item_userdata = userdata;
    TrackedHtml tracked_html;
    tracked_html.plugin = plugin;
    tracked_html.title = title;
    tracked_html.link = link;
    tracked_html.json_data = json_data;
    return sync_html(&tracked_html, iterate_html_item_userdata->program_dir, iterate_html_item_userdata->download_dir, config_dir);
}

static void sync_tracked_rss(TransmissionSession *transmission_session, char *rss_config_dir) {
    iterate_tracked_items(rss_config_dir, iterate_tracked_item_rss_callback, transmission_session);
}

static void sync_tracked_html(char *html_config_dir, char *program_dir, const char *download_dir) {
    IterateHtmlItemUserdata iterate_html_item_userdata;
    iterate_html_item_userdata.program_dir = program_dir;
    iterate_html_item_userdata.download_dir = download_dir;
    iterate_tracked_items(html_config_dir, iterate_tracked_item_html_callback, &iterate_html_item_userdata);
}

typedef struct {
    char *items;
    int size;
} UnfinishedTorrents;

static void torrent_list_check_new_downloads_callback(int id, const char *name, double percentage_done, void *userdata) {
    /* Sanity check, random high number */
    if(id <= 0 || id >= 650000) {
        fprintf(stderr, "Invalid torrent id: %d\n", id);
        return;
    }

    id--;
    UnfinishedTorrents *unfinished_torrents = userdata;

    int is_finished = (percentage_done >= 0.9999);
    if(is_finished) {
        if(id < unfinished_torrents->size && unfinished_torrents->items[id] == 1) {
            unfinished_torrents->items[id] = 0;
            const char *notify_args[] = { "notify-send", "-u", "normal", "-t", "10000", "--", "Download finished", name, NULL };
            program_exec(notify_args, NULL, NULL);
        }
    } else {
        if(id >= unfinished_torrents->size) {
            int prev_size = unfinished_torrents->size;
            unfinished_torrents->size = id + 128;
            unfinished_torrents->items = realloc_or_crash(unfinished_torrents->items, unfinished_torrents->size);
            memset(unfinished_torrents->items + prev_size, 0, unfinished_torrents->size - prev_size);
        }
        unfinished_torrents->items[id] = 1;
    }
}

static void sync_rss_html(char *rss_config_dir, char *html_config_dir, char *program_dir, const char *download_dir, int sync_rate_sec) {
    if(transmission_is_daemon_running() != 0) {
        if(transmission_start_daemon(download_dir) != 0) {
            fprintf(stderr, "Failed to start torrent daemon\n");
            exit(2);
        }
    }

    TransmissionSession transmission_session;
    if(transmission_connect(&transmission_session) != 0) {
        fprintf(stderr, "Failed to connect to the transmission daemon!\n");
        exit(2);
    }

    /* Check for torrent progress every 15 seconds */
    int check_torrent_status_rate_sec = 15;

    UnfinishedTorrents unfinished_torrents;
    unfinished_torrents.size = 1024;
    unfinished_torrents.items = alloc_or_crash(unfinished_torrents.size);
    memset(unfinished_torrents.items, 0, unfinished_torrents.size);

    automedia_running = 1;
    transmission_list_torrents(&transmission_session, torrent_list_check_new_downloads_callback, &unfinished_torrents);
    /* running is set to 0 in SIGINT signal handler (ctrl+c) */
    while(automedia_running) {
        sync_tracked_rss(&transmission_session, rss_config_dir);
        sync_tracked_html(html_config_dir, program_dir, download_dir);
        fprintf(stderr, "Finished syncing rss and html. Syncing again in 15 minutes\n");

        int check_count = 0;
        while(automedia_running && check_count < sync_rate_sec/check_torrent_status_rate_sec) {
            transmission_list_torrents(&transmission_session, torrent_list_check_new_downloads_callback, &unfinished_torrents);
            sleep(check_torrent_status_rate_sec);
            ++check_count;
        }
    }

    free(unfinished_torrents.items);
}

static int cmdline_contains_str(const char *cmdline, int cmdline_len, const char *str) {
    const char *start = cmdline;
    while(cmdline - start < cmdline_len) {
        int arg_len = strlen(cmdline);
        if(arg_len == 0)
            return -1;

        if(strstr(cmdline, str))
            return 0;

        cmdline += arg_len + 1;
    }
    return -1;
}

/* We can't use file_get_content because reading the size of /proc/<pid>/cmdline fails (returns 0) because its not a regular file */
static int proc_read_cmdline(const char *pid_str, char *cmdline_data, int cmdline_data_size, int *cmdline_data_size_output) {
    assert(cmdline_data_size > 0);

    char cmdline_file_path[256];
    snprintf(cmdline_file_path, sizeof(cmdline_file_path), "/proc/%s/cmdline", pid_str);

    int cmdline_fd = open(cmdline_file_path, O_RDONLY);
    if(cmdline_fd == -1) {
        fprintf(stderr, "Process %s doesn't exist\n", pid_str);
        return -1;
    }

    ssize_t bytes_read = read(cmdline_fd, cmdline_data, cmdline_data_size - 1);
    if(bytes_read == -1) {
        fprintf(stderr, "Failed to read %s\n", cmdline_file_path);
        close(cmdline_fd);
        return -1;
    }

    cmdline_data[bytes_read] = '\0';
    *cmdline_data_size_output = bytes_read;
    close(cmdline_fd);
    return 0;
}

static int run_mangadex_migration_script() {
    const char *args[] = { "/usr/share/automedia/mangadex-upgrade.py", NULL };
    return program_exec(args, NULL, NULL);
}

static void command_sync(int argc, char **argv, char *rss_config_dir, char *html_config_dir, char *program_dir) {
    if(argc < 1)
        usage_sync();

    if(run_mangadex_migration_script() != 0) {
        fprintf(stderr, "Failed to migrade mangadex manga\n");
        exit(1);
    }

    char *download_dir = argv[0];
    const char automedia_pid_path[] = "/tmp/automedia.pid";

    if(create_directory_recursive(download_dir) != 0) {
        fprintf(stderr, "Failed to create download directory %s\n", download_dir);
        exit(1);
    }
    
    /* Create a pid file because we only want to allow one instance of automedia to run at once */
    int pid_file = open(automedia_pid_path, O_CREAT | O_EXCL | O_SYNC | O_RDWR, 0666);
    if(pid_file == -1 && errno == EEXIST) {
        char *running_automedia_pid;
        long running_automedia_pid_size;
        if(file_get_content(automedia_pid_path, &running_automedia_pid, &running_automedia_pid_size) == 0) {
            /*
                We have to check the cmdline because another process could theoretically receive the pid
                that an old automedia process had
            */
            char cmdline[1024];
            int cmdline_size;
            if(proc_read_cmdline(running_automedia_pid, cmdline, sizeof(cmdline), &cmdline_size) == 0
                && cmdline_contains_str(cmdline, cmdline_size, "automedia") == 0
                && cmdline_contains_str(cmdline, cmdline_size, "sync") == 0) {
                fprintf(stderr, "Automedia is already running with sync\n");
                free(running_automedia_pid);
                exit(1);
            }
            free(running_automedia_pid);
        } else {
            fprintf(stderr, "Failed to get content of %s\n", automedia_pid_path);
            exit(1);
        }

        fprintf(stderr, "Overwriting existing %s\n", automedia_pid_path);
        remove(automedia_pid_path);
        pid_file = open(automedia_pid_path, O_CREAT | O_EXCL | O_SYNC | O_RDWR, 0666);
    }

    if(pid_file == -1 && errno != EEXIST) {
        fprintf(stderr, "Failed to create %s\n", automedia_pid_path);
        exit(1);
    }

    signal(SIGINT, automedia_pid_signal_handler);

    char process_pid_str[32];
    snprintf(process_pid_str, sizeof(process_pid_str), "%d", getpid());
    int process_pid_str_len = strlen(process_pid_str);
    if(write(pid_file, process_pid_str, process_pid_str_len) != process_pid_str_len) {
        fprintf(stderr, "Failed to write pid to %s\n", automedia_pid_path);
        remove(automedia_pid_path);
        exit(1);
    }

    close(pid_file);
    const int sync_rate_sec = 15 * 60; /* every 15 min */
    sync_rss_html(rss_config_dir, html_config_dir, program_dir, download_dir, sync_rate_sec);
    remove(automedia_pid_path);
}

static void command_downloaded(const char *rss_config_dir, const char *html_config_dir) {
    char rss_tracked_dir[PATH_MAX];
    strcpy(rss_tracked_dir, rss_config_dir);
    strcat(rss_tracked_dir, "/tracked");

    char html_tracked_dir[PATH_MAX];
    strcpy(html_tracked_dir, html_config_dir);
    strcat(html_tracked_dir, "/tracked");

    Buffer downloaded_items;
    buffer_init(&downloaded_items);

    get_downloaded_items(rss_tracked_dir, 0, &downloaded_items);
    get_downloaded_items(html_tracked_dir, 1, &downloaded_items);

    qsort(downloaded_items.data, buffer_get_size(&downloaded_items, sizeof(DownloadedListData)), sizeof(DownloadedListData), compare_downloaded_item);
    DownloadedListData *list_it = buffer_begin(&downloaded_items);
    DownloadedListData *list_end = buffer_end(&downloaded_items);
    for(; list_it != list_end; ++list_it) {
        puts(list_it->title);
        free(list_it->title);
    }

    buffer_deinit(&downloaded_items);
}

const char* path_get_filename(const char *filepath) {
    int len = strlen(filepath);
    for(int i = len - 1; i >= 0; --i) {
        if(filepath[i] == '/')
            return filepath + i + 1;
    }
    return filepath;
}

static int compare_tracked_item(const void *a, const void *b) {
    const TrackedItemData *list_data_a = a;
    const TrackedItemData *list_data_b = b;
    return list_data_a->updated_time - list_data_b->updated_time;
}

static void command_cleanup(int argc, char **argv, const char *rss_config_dir, const char *html_config_dir) {
    time_t days = 0;
    if(argc >= 1) {
        errno = 0;
        days = strtol(argv[0], NULL, 0);
        if(errno || days < 0) {
            fprintf(stderr, "Invalid value for days argument %s, expected a positive number\n", argv[0]);
            usage_cleanup();
        }
    }

    char rss_tracked_dir[PATH_MAX];
    strcpy(rss_tracked_dir, rss_config_dir);
    strcat(rss_tracked_dir, "/tracked");

    char html_tracked_dir[PATH_MAX];
    strcpy(html_tracked_dir, html_config_dir);
    strcat(html_tracked_dir, "/tracked");

    Buffer tracked_items;
    buffer_init(&tracked_items);

    int num_rss_items = 0;
    const time_t age_sec = 60 * 60 * 24 * days;
    get_tracked_items(rss_tracked_dir, age_sec, &tracked_items);
    num_rss_items = buffer_get_size(&tracked_items, sizeof(TrackedItemData));
    get_tracked_items(html_tracked_dir, age_sec, &tracked_items);
    int num_tracked_items = buffer_get_size(&tracked_items, sizeof(TrackedItemData));

    qsort(tracked_items.data, num_rss_items, sizeof(TrackedItemData), compare_tracked_item);
    qsort((TrackedItemData*)tracked_items.data + num_rss_items, num_tracked_items - num_rss_items, sizeof(TrackedItemData), compare_tracked_item);

    TrackedItemData *list_begin = buffer_begin(&tracked_items);
    TrackedItemData *list_it = list_begin;
    TrackedItemData *list_end = buffer_end(&tracked_items);
    int index = 0;
    for(; list_it != list_end; ++list_it) {
        const char *name = path_get_filename(list_it->item_tracked_path);
        printf("%d %s/%s\n", 1 + index, index < num_rss_items ? "rss" : "html", name);
        ++index;
    }

    char *track_items_selected = alloc_or_crash(num_tracked_items);
    Buffer /*size_t*/ tracks_to_remove;
    buffer_init(&tracks_to_remove);

    Buffer /*Range*/ track_remove_ranges;
    buffer_init(&track_remove_ranges);

    if(tracked_items.size == 0) {
        fprintf(stderr, "There is no media that hasn't been updated in the last %ld %s\n", days, days == 1 ? "day" : "days");
        goto cleanup;
    }

    for(;;) {
        fprintf(stderr, "==> Media to stop tracking: (eg: 10, 1-3)\n");
        fprintf(stderr, "==> ");
        fflush(stderr);

        char resp[512];
        if(!fgets(resp, sizeof(resp), stdin)) {
            fprintf(stderr, "Failed to read response from stdin\n");
            goto cleanup;
        }

        char *response_str = strip(resp);
        int response_len = strlen(response_str);
        if(response_len == 0) {
            fprintf(stderr, "Invalid input. Expected numbers and/or number ranges\n");
            continue;
        }

        memset(track_items_selected, 0, num_tracked_items);
        buffer_clear(&tracks_to_remove);
        buffer_clear(&track_remove_ranges);

        if(track_remove_parser_parse(response_str, response_len, &track_remove_ranges) != 0)
            continue;

        Range *track_remove_it = buffer_begin(&track_remove_ranges);
        Range *track_remove_end = buffer_end(&track_remove_ranges);

        int valid_ranges = 1;
        for(; track_remove_it != track_remove_end; ++track_remove_it) {
            int start_index_f = track_remove_it->start - 1;
            if(start_index_f < 0 || start_index_f >= num_tracked_items) {
                fprintf(stderr, "Invalid item start range: %d, expected a value between 1 and %d\n", track_remove_it->start, num_tracked_items);
                valid_ranges = 0;
                break;
            }

            int end_index_f = track_remove_it->end - 1;
            if(end_index_f < start_index_f || end_index_f >= num_tracked_items) {
                fprintf(stderr, "Invalid item end range: %d, expected a value between %d and %d\n", end_index_f, track_remove_it->start, num_tracked_items);
                valid_ranges = 0;
                break;
            }

            for(size_t i = start_index_f; i <= (size_t)end_index_f; ++i) {
                if(track_items_selected[i])
                    continue;

                track_items_selected[i] = 1;
                buffer_append(&tracks_to_remove, &i, sizeof(i));
            }
        }

        if(!valid_ranges)
            continue;

        for(;;) {
            size_t *tracks_to_remove_it = buffer_begin(&tracks_to_remove);
            size_t *tracks_to_remove_end = buffer_end(&tracks_to_remove);
            fprintf(stderr, "==> Are you sure you want to stop tracking:\n");
            for(; tracks_to_remove_it != tracks_to_remove_end; ++tracks_to_remove_it) {
                const size_t track_index = *tracks_to_remove_it;
                TrackedItemData *track_item = &list_begin[track_index];
                const char *name = path_get_filename(track_item->item_tracked_path);
                printf("  %s/%s\n", track_index < (size_t)num_rss_items ? "rss" : "html", name);
            }

            fprintf(stderr, "==> Yes/No: ");
            fflush(stderr);

            if(!fgets(resp, sizeof(resp), stdin)) {
                fprintf(stderr, "Failed to read response from stdin\n");
                goto cleanup;
            }

            response_str = strip(resp);
            response_len = strlen(response_str);
            if(response_len == 0)
                continue;

            if(response_str[0] == 'n' || response_str[0] == 'N') {
                goto cleanup;
            } else if(response_str[0] == 'y' || response_str[0] == 'Y') {
                break;
            }
        }

        size_t *tracks_to_remove_it = buffer_begin(&tracks_to_remove);
        size_t *tracks_to_remove_end = buffer_end(&tracks_to_remove);
        for(; tracks_to_remove_it != tracks_to_remove_end; ++tracks_to_remove_it) {
            const size_t track_index = *tracks_to_remove_it;
            TrackedItemData *track_item = &list_begin[track_index];
            const char *name = path_get_filename(track_item->item_tracked_path);
            if(remove_recursive(track_item->item_tracked_path) != 0) {
                fprintf(stderr, "Failed to remove %s/%s\n", track_index < (size_t)num_rss_items ? "rss" : "html", name);
                goto cleanup;
            }
            fprintf(stderr, "Removed %s/%s\n", track_index < (size_t)num_rss_items ? "rss" : "html", name);
        }
        break;
    }

    cleanup:
    buffer_deinit(&track_remove_ranges);
    buffer_deinit(&tracks_to_remove);
    free(track_items_selected);

    list_it = buffer_begin(&tracked_items);
    list_end = buffer_end(&tracked_items);
    for(; list_it != list_end; ++list_it) {
        free(list_it->item_tracked_path);
    }
    buffer_deinit(&tracked_items);
}

int main(int argc, char **argv) {
    if(argc < 2)
        usage();

    setlocale(LC_ALL, "C");

    const char *home_dir = get_home_dir();

    char rss_config_dir[PATH_MAX];
    strcpy(rss_config_dir, home_dir);
    strcat(rss_config_dir, "/.config/automedia/rss");

    char html_config_dir[PATH_MAX];
    strcpy(html_config_dir, home_dir);
    strcat(html_config_dir, "/.config/automedia/html");

    const char *command = argv[1];
    if(strcmp(command, "add") == 0) {
        command_add(argc - 2, argv + 2, rss_config_dir, html_config_dir, dirname(argv[0]));
    } else if(strcmp(command, "sync") == 0) {
        command_sync(argc - 2, argv + 2, rss_config_dir, html_config_dir, dirname(argv[0]));
    } else if(strcmp(command, "downloaded") == 0) {
        command_downloaded(rss_config_dir, html_config_dir);
    } else if(strcmp(command, "cleanup") == 0) {
        command_cleanup(argc - 2, argv + 2, rss_config_dir, html_config_dir);
    } else {
        fprintf(stderr, "Error: Invalid command %s\n", command);
        usage();
    }

    return 0;
}