1 #include <stdio.h>
2 #include <string.h>
3 #include <shadowdive/shadowdive.h>
4 
5 #include "resources/sgmanager.h"
6 #include "resources/pathmanager.h"
7 #include "utils/scandir.h"
8 #include "utils/list.h"
9 #include "utils/log.h"
10 
sg_init()11 int sg_init() {
12     int ret;
13     list dirlist;
14 
15     // Find path to savegame directory
16     const char* dirname = pm_get_local_path(SAVE_PATH);
17     if(dirname == NULL) {
18         PERROR("Could not find save path! Something is wrong with path manager!");
19         return 1;
20     }
21 
22     // Seek all files
23     list_create(&dirlist);
24     ret = scan_directory(&dirlist, dirname);
25     if(ret != 0) {
26         INFO("Savegame directory does not exist. Attempting to create ...");
27         if(pm_create_dir(dirname) != 0) {
28             PERROR("Unable to create savegame directory!");
29             goto error_0;
30         } else {
31             INFO("Savegame directory created at '%s'.", dirname);
32         }
33 
34         // New attempt
35         ret = scan_directory(&dirlist, dirname);
36         if(ret != 0) {
37             PERROR("Still cound not read from savegame directory, giving up.");
38             goto error_0;
39         }
40     }
41 
42     // TODO: Handle looking up saves properly. Now just list_size - 2 (.. and .)
43     DEBUG("Found %d savegames.", list_size(&dirlist)-2);
44 
45     list_free(&dirlist);
46     return 0;
47 
48 error_0:
49     list_free(&dirlist);
50     return 1;
51 }
52 
sg_load(sd_pilot * pilot,const char * pilotname)53 int sg_load(sd_pilot *pilot, const char* pilotname) {
54     char tmp[1024];
55 
56     // Form the savegame filename
57     const char* dirname = pm_get_local_path(SAVE_PATH);
58     snprintf(tmp, 1024, "%s/%s.CHR", dirname, pilotname);
59 
60     // Attempt to load
61     sd_chr_file chr;
62     sd_chr_create(&chr);
63     int ret = sd_chr_load(&chr, tmp);
64     if(ret != SD_SUCCESS) {
65         PERROR("Unable to load savegame file '%s'.", tmp);
66         return 1;
67     }
68     memcpy(pilot, &chr.pilot, sizeof(sd_pilot));
69     sd_chr_free(&chr);
70 
71     return 0;
72 }
73 
sd_save(const sd_pilot * pilot,const char * pilotname)74 int sd_save(const sd_pilot *pilot, const char* pilotname) {
75     // Report error for now
76     return 1;
77 }