walnut 0.1.5

# Walnut File Systwm Experimental file system with inode level encryption.
Documentation
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
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
use anyhow::anyhow;
use bitvec::{order::Lsb0, vec::BitVec};
use serde::{Deserialize, Serialize};
use std::fs::{File, OpenOptions};
use std::io::{BufRead, BufReader, BufWriter, Cursor, Seek, SeekFrom};
use std::{
    collections::BTreeMap,
    ffi::OsString,
    io::{Read, Write},
    path::Path,
};

use util::*;

const MAGIC: [u8; 7] = *b"*bitfs*";
// const TEST_BYTES: [u8; 20] = *b"canureadthistextbro?";
const FS_VERSION: u32 = 1;
const ROOT_INODE_INDEX: u32 = 2;
const BLOCK_SIZE: u32 = 4096;
const BLOCKS_PER_GROUP: u32 = BLOCK_SIZE * 8;
const INODE_CAPACITY: usize = 4047;
const INODE_MAX_REGION: usize = 500;

pub mod util;

#[derive(Debug)]
pub struct FS {
    pub superblock: Superblock,
    pub file: File,
    pub groups: Vec<Group>,
    pub lookup_table: Vec<u8>,
}

impl FS {
    /// Init FS to a given path
    pub fn init<P>(path: P, secret: &str) -> anyhow::Result<Self>
    where
        P: AsRef<Path>,
    {
        // Create path if it has not exist (yet)
        // Fails if path does exist
        let file = OpenOptions::new()
            .read(true)
            .write(true)
            .create_new(true)
            .open(path.as_ref())?;

        // Create mmap from file
        // let mmap = unsafe { MmapMut::map_mut(&file)? };

        let superblock = Superblock::new();

        let mut fs = Self {
            superblock,
            file,
            groups: vec![],
            lookup_table: create_lookup_table(secret.as_bytes(), BLOCK_SIZE),
        };

        // Create group
        let mut group = Group::init();

        // Set root inode index as allocated
        group.force_allocate_at(0);

        // Add to superblock
        fs.add_group(group)?;

        // Create directory_index
        fs.init_directory_index()?;

        Ok(fs)
    }

    /// Open FS from a given path
    pub fn new<P>(path: P, secret: &str) -> anyhow::Result<Self>
    where
        P: AsRef<Path>,
    {
        // Open image path as read & write
        let mut file = OpenOptions::new()
            .read(true)
            .write(true)
            .open(path.as_ref())?;

        let mut r = BufReader::new(&mut file);

        r.seek(SeekFrom::Start(0))?;

        // Deserialize superblock from cursor
        let superblock: Superblock = Superblock::deserialize_from(&mut r)?;

        let mut groups = vec![];

        // Deserialize groups based on superblock group count
        for group_index in 0..superblock.group_count {
            let group = Group::deserialize_from(&mut r, group_index)?;
            groups.push(group);
        }

        let fs = Self {
            superblock,
            groups,
            file,
            lookup_table: create_lookup_table(secret.as_bytes(), BLOCK_SIZE),
        };

        // Return FS
        Ok(fs)
    }

    #[inline]
    pub fn get_directory_index(&self) -> anyhow::Result<DirectoryIndex> {
        // Get inode
        let mut inode = self.get_inode(ROOT_INODE_INDEX)?;

        // Read inode data
        let mut data = vec![];

        {
            let mut w = BufWriter::new(&mut data);
            self.read_inode_data(&mut inode, &mut w)?;
        }

        // Deserialize
        let mut directory_index: DirectoryIndex = bincode::deserialize(&data)?;

        if !directory_index.verify_checksum() {
            return Err(anyhow!("Directory index checksum error"));
        }

        Ok(directory_index)
    }

    fn save_directory_index(&mut self, mut directory_index: DirectoryIndex) -> anyhow::Result<()> {
        let mut inode = self.get_inode(ROOT_INODE_INDEX)?;

        // Set checksum
        directory_index.checksum();

        let data = bincode::serialize(&directory_index)?;
        let mut w = Cursor::new(&data);

        // Save directory
        self.write_inode_data(&mut inode, &mut w, data.len() as u64)?;

        Ok(())
    }

    fn init_directory_index(&mut self) -> anyhow::Result<()> {
        let di = DirectoryIndex::init();

        let di_data = bincode::serialize(&di)?;
        let mut r = Cursor::new(&di_data);

        let mut directory_index_inode = Inode::new(ROOT_INODE_INDEX);

        self.save_inode(&mut directory_index_inode)?;

        self.write_inode_data(&mut directory_index_inode, &mut r, di_data.len() as u64)?;

        Ok(())
    }

    /// Find directory
    /// returns directory and its inode index
    #[inline]
    pub fn find_directory<P>(&self, dir: P) -> anyhow::Result<(Directory, u32)>
    where
        P: AsRef<Path>,
    {
        // First get directory index
        let directory_index = self.get_directory_index()?;

        // Find directory in dir.index
        if let Some(directory_inode_index) = directory_index.find_dir(dir) {
            // Get directory inode
            let mut directory_inode = self.get_inode(*directory_inode_index)?;

            let mut data = Vec::new();

            // Read inode data
            {
                let mut w = BufWriter::new(&mut data);
                self.read_inode_data(&mut directory_inode, &mut w)?;
            }

            // Deserialize directory
            let directory: Directory = bincode::deserialize(&data)?;

            // Return it
            return Ok((directory, *directory_inode_index));
        } else {
            return Err(anyhow!("Directory not found"));
        }
    }

    #[inline]
    fn save_directory(
        &mut self,
        directory: Directory,
        directory_inode_index: u32,
    ) -> anyhow::Result<Directory> {
        // Get directory inode
        let mut directory_inode = self.get_inode(directory_inode_index)?;

        // Serialize directory
        let data = bincode::serialize(&directory)?;
        let mut reader = Cursor::new(&data);

        self.write_inode_data(&mut directory_inode, &mut reader, data.len() as u64)?;

        Ok(directory)
    }

    /// Create directory
    /// returns created directory
    #[inline]
    pub fn create_directory<P>(&mut self, dir: P) -> anyhow::Result<Directory>
    where
        P: AsRef<Path>,
    {
        // First get directory index
        let mut directory_index = self.get_directory_index()?;

        // Then allocate dir inode index
        let directory_inode = if let Some(i) = self.allocate_inode() {
            i
        } else {
            return Err(anyhow!("Could not allocate inode block"));
        };

        // Then try to add directory to dir index
        // If it fails, then free up allocated block
        if let None = directory_index.create_dir(dir, directory_inode.block_index) {
            self.release_inode(directory_inode.block_index)?;
        }

        // Save directory index
        self.save_directory_index(directory_index)?;

        // Create empty directory
        let directory = Directory::init();

        // Try to save directory
        self.save_directory(directory, directory_inode.block_index)
    }

    /// Get file by dir and filename
    /// returns found file inode
    #[inline]
    pub fn get_file_info<P>(&mut self, dir: P, file_name: &str) -> anyhow::Result<Inode>
    where
        P: AsRef<Path>,
    {
        // Check if dir exist
        let (dir, _dir_inode_index) = self.find_directory(dir)?;

        // Find file
        if let Some(inode_block_index) = dir.get_file(file_name) {
            return self.get_inode(inode_block_index);
        } else {
            return Err(anyhow!("File not found"));
        }
    }

    /// Create a file at a given dir
    /// with a given name
    /// Copy data to the given file
    /// data_len (bytes) must be correct
    #[inline]
    pub fn add_file<P, R>(
        &mut self,
        dir: P,
        file_name: &str,
        data: &mut R,
        data_len: u64,
    ) -> anyhow::Result<()>
    where
        P: AsRef<Path>,
        R: BufRead,
    {
        // Check if dir exist
        let (mut dir, dir_inode_index) = self.find_directory(dir)?;

        // Find file
        let mut file_inode = if let Some(inode_block_index) = dir.get_file(file_name) {
            self.get_inode(inode_block_index)?
        } else {
            let file_inode = self.allocate_inode().unwrap();
            dir.add_file(file_name, file_inode.block_index)?;
            self.save_directory(dir, dir_inode_index)?;

            // Inc. file count
            self.superblock_mut().file_count += 1;

            file_inode
        };

        self.write_inode_data(&mut file_inode, data, data_len)?;

        // Save superblock
        self.save_superblock()?;

        Ok(())
    }

    #[inline]
    pub fn remove_file(&mut self, dir: &str, file_name: &str) -> anyhow::Result<()> {
        // Check if dir exist
        let (mut dir, dir_inode_index) = self.find_directory(dir)?;

        // Find file
        let file_inode = if let Some(inode_block_index) = dir.get_file(file_name) {
            if let Ok(inode) = self.get_inode(inode_block_index) {
                inode
            } else {
                return Err(anyhow!("No file found in dir!"));
            }
        } else {
            return Err(anyhow!("Unknown directory!"));
        };

        // Release inode
        self.release_inode(file_inode.block_index)?;

        // Remove file from directory
        dir.remove_file(file_name)?;

        // Save directory
        self.save_directory(dir, dir_inode_index)?;

        // Save superblock
        self.save_superblock()?;

        Ok(())
    }

    /// Read file data
    /// Finds file by dir and filename
    /// And writes its content to the given writer
    #[inline]
    pub fn get_file_data<P, W>(&mut self, dir: P, file_name: &str, w: &mut W) -> anyhow::Result<u32>
    where
        P: AsRef<Path>,
        W: Write,
    {
        // First find directory
        let (directory, _) = self.find_directory(dir)?;

        // Then find file
        let mut file_inode = if let Some(file_inode_index) = directory.get_file(file_name) {
            self.get_inode(file_inode_index)?
        } else {
            // Else return error
            return Err(anyhow!("File not found"));
        };

        self.read_inode_data(&mut file_inode, w)
    }

    #[inline]
    fn superblock_check(&mut self) {
        // Set group count
        self.superblock.group_count = self.groups.len() as u32;
        // Set free blocks
        self.superblock.free_blocks = self
            .groups
            .iter()
            .map(|g| g.block_bitmap.count_zeros() as u32)
            .sum();
        // Set block count
        self.superblock.block_count = self
            .groups
            .iter()
            .map(|g| g.total_data_blocks() as u32)
            .sum();
        // Set last modified time
        self.superblock.modified = now();
        // Set checksum
        self.superblock.checksum();
    }

    #[inline]
    fn save_superblock(&mut self) -> anyhow::Result<()> {
        // Create superblock checks
        self.superblock_check();

        let mut w = BufWriter::new(&self.file);
        let mut data = bincode::serialize(&self.superblock)?;
        w.seek(SeekFrom::Start(0))?;
        w.write_all(&mut data)?;
        Ok(())
    }

    #[inline]
    fn get_inode(&self, inode_block_index: u32) -> anyhow::Result<Inode> {
        let mut r = BufReader::new(&self.file);

        r.seek(SeekFrom::Start(
            block_seek_position(inode_block_index) as u64
        ))?;

        // Deserialize by bincode
        let inode: Inode = Inode::deserialize_from(r)?;

        // Return inode
        Ok(inode)
    }

    #[inline]
    fn save_inode(&mut self, inode: &mut Inode) -> anyhow::Result<()> {
        let mut w = BufWriter::new(&self.file);

        w.seek(SeekFrom::Start(
            block_seek_position(inode.block_index) as u64
        ))?;
        inode.set_last_modified();
        inode.serialize_into(w)?;
        Ok(())
    }

    #[inline]
    fn save_group(&mut self, group: Group, group_index: u32) -> anyhow::Result<()> {
        // Update group at FS
        self.groups[group_index as usize] = group.clone();

        // Write group to disk
        let mut w = BufWriter::new(&self.file);

        w.seek(SeekFrom::Start(Group::seek_position(group_index) as u64))?;
        group.serialize_into(w)?;
        Ok(())
    }

    #[inline]
    fn read_inode_data<W>(&self, inode: &mut Inode, w: &mut W) -> anyhow::Result<u32>
    where
        W: Write,
    {
        let mut checksum = Checksum::new();
        let mut r = BufReader::new(&self.file);

        match &mut inode.data {
            Data::Raw(data) => {
                // Decrypt raw data
                encrypt(data, &self.lookup_table);

                // Update checksum
                checksum.update(&data);

                // Write data into writer
                w.write_all(&data)?;
            }
            Data::DirectPointers(pointers) => {
                // Counting data left to read
                let mut data_left = inode.size;

                let mut block_buffer: Vec<u8> = Vec::with_capacity(BLOCK_SIZE as usize);
                unsafe { block_buffer.set_len(BLOCK_SIZE as usize) };

                for (block_index, range) in pointers {
                    // Seek start position
                    r.seek(SeekFrom::Start(block_seek_position(*block_index) as u64))?;

                    for _ in *block_index..(*block_index + *range) {
                        // Determine if last block
                        if data_left < BLOCK_SIZE as u64 {
                            block_buffer = Vec::with_capacity(data_left as usize);
                            unsafe { block_buffer.set_len(data_left as usize) };
                        };

                        // Read range bytes
                        r.read_exact(&mut block_buffer)?;

                        // Decrypt chunk
                        encrypt(&mut block_buffer, &self.lookup_table);

                        // Update checksum
                        checksum.update(&block_buffer);

                        // Write buffer to writer
                        w.write_all(&mut block_buffer)?;
                        // std::io::copy(&mut BufReader::new(Cursor::new(&block_buffer)), &mut w)?;

                        // Decrease data_left
                        data_left -= block_buffer.capacity() as u64;
                    }
                }
            }
        }

        Ok(checksum.finalize())
    }

    #[inline]
    fn write_inode_data<R>(
        &mut self,
        inode: &mut Inode,
        data: &mut R,
        data_len: u64,
    ) -> anyhow::Result<()>
    where
        R: BufRead,
    {
        // Release inode data
        match &inode.data {
            Data::Raw(_) => (),
            Data::DirectPointers(pointers) => self.release_inode_data(pointers.clone())?,
        }

        // If data length fits inside inode
        if data_len as usize <= INODE_CAPACITY {
            // Create buffer
            let mut buffer = vec![];

            // and read data into it
            data.read_to_end(&mut buffer)?;

            // Encrypt buffer
            encrypt(&mut buffer, &self.lookup_table);

            // Create reader from buffer
            let mut data = Cursor::new(&buffer);

            // Set data inside inode
            inode.set_raw_data(&mut data, data_len)?;

            // Save inode
            self.save_inode(inode)?;

            // Return ok
            return Ok(());
        }

        // If data does not fit inside Inode as raw data

        // Set inode data size
        inode.size = data_len;
        // And save it
        self.save_inode(inode)?;

        // Define empty ranges
        let mut ranges: Vec<(u32, u32)> = vec![];

        // Define block_to_allocate
        let blocks_to_allocate = |data_size| {
            data_size / BLOCK_SIZE as u64 + u64::from(data_size % BLOCK_SIZE as u64 != 0)
        };

        // Determine how many block we need
        let mut block_to_allocate = blocks_to_allocate(data_len);

        // Check if we have enough space for file
        while self.superblock().free_blocks < block_to_allocate as u32 {
            // Add new group
            self.add_group(Group::init())?;
        }

        let groups = self.groups.clone();

        for (group_index, mut group) in groups.into_iter().enumerate() {
            // Check if we need any blocks?
            if block_to_allocate > 0 {
                // Allocate regions from group
                let (mut range, left) = group.allocate_region(
                    group_index as u32,
                    block_to_allocate as usize,
                    INODE_MAX_REGION,
                );

                // Save group
                self.save_group(group, group_index as u32)?;

                ranges.append(&mut range);

                // Decrease block wanted
                block_to_allocate = left as u64;
            }
        }

        // Save ranges
        inode.set_direct_pointers(ranges.clone(), data_len);
        self.save_inode(inode)?;

        // Write data into ranges
        let mut data_left = data_len;

        let mut w = BufWriter::new(&self.file);

        let mut block_buffer: Vec<u8> = Vec::with_capacity(BLOCK_SIZE as usize);
        unsafe { block_buffer.set_len(BLOCK_SIZE as usize) };

        for (block_index, range) in ranges {
            // Seek position
            w.seek(SeekFrom::Start(block_seek_position(block_index) as u64))?;

            // Iter over rage
            for _ in block_index..(block_index + range) {
                // Determine if last block
                if data_left < BLOCK_SIZE as u64 {
                    block_buffer = Vec::with_capacity(data_left as usize);
                    unsafe { block_buffer.set_len(data_left as usize) };
                };

                // Read data into chunk buffer
                data.read_exact(&mut block_buffer)?;

                // Encrypt chunk
                encrypt(&mut block_buffer, &self.lookup_table);

                // Write chunk buffer to disk
                w.write_all(&mut block_buffer)?;

                // Decrease data left
                data_left -= block_buffer.capacity() as u64;
            }
        }

        // Check all data has written
        assert!(data_left == 0);

        // Flush disk
        w.flush()?;

        Ok(())
    }

    #[inline]
    fn truncate(&mut self) -> anyhow::Result<()> {
        // Superblock + GroupCount * (Group bitmap + group data inodes)
        let size =
            BLOCK_SIZE + (self.groups.len() as u32) * (BLOCK_SIZE + BLOCKS_PER_GROUP * BLOCK_SIZE);
        // Set file size
        self.file.set_len(size as u64)?;
        // Return ok
        Ok(())
    }

    #[inline]
    fn allocate_inode(&mut self) -> Option<Inode> {
        // Check if we need more space
        // while self.superblock().free_blocks < 3 {
        //     self.add_group(Group::init()).unwrap();
        // }

        let mut res = None;
        for (group_index, group) in self.groups_mut().iter_mut().enumerate() {
            if let Some(inode_block_index) = group.allocate_one(group_index as u32) {
                let inode = Inode::new(inode_block_index);
                res = Some(inode);
                break;
            }
        }
        if let Some(inode) = &mut res {
            self.save_inode(inode).unwrap();
        }
        // TODO! Shoud handle the case when inode fails to save
        res
    }

    #[inline]
    fn add_group(&mut self, group: Group) -> anyhow::Result<()> {
        // Insert new group to FS groups
        self.groups.push(group.clone());
        // Save group to disk
        self.save_group(group, self.groups.len() as u32 - 1)?;
        // Increment group count
        self.superblock.group_count += 1;
        // Truncate itself
        self.truncate()?;
        // Save superblock
        self.save_superblock()?;
        // Return ok
        Ok(())
    }

    #[inline]
    fn groups_mut(&mut self) -> &mut [Group] {
        &mut self.groups
    }

    #[inline]
    fn superblock(&self) -> &Superblock {
        &self.superblock
    }

    #[inline]
    fn superblock_mut(&mut self) -> &mut Superblock {
        &mut self.superblock
    }

    #[inline]
    fn release_inode_data(&mut self, data_pointers: Vec<(u32, u32)>) -> anyhow::Result<()> {
        let mut groups = self.groups_mut().as_mut().to_owned();

        // Check each data region
        for (block_index, range) in data_pointers {
            // Translate public address
            let (group_index, bitmap_index) = Group::translate_public_address(block_index);
            // Release data region
            groups[group_index as usize].release_data_region(bitmap_index, range);
        }
        // Iter groups
        for (group_index, group) in groups.into_iter().enumerate() {
            {
                // And save each group to disk
                self.save_group(group, group_index as u32)?;
            }
        }
        Ok(())
    }

    #[inline]
    fn release_inode(&mut self, inode_block_index: u32) -> anyhow::Result<()> {
        // Check if inode exist
        let inode = self.get_inode(inode_block_index)?;

        // Translate block index
        let (group_index, bitmap_index) = Group::translate_public_address(inode_block_index);

        // Release data
        match inode.data {
            // Dont do anything when it has raw data
            Data::Raw(_) => (),
            // Release all direct pointers
            Data::DirectPointers(direct_pointers) => self.release_inode_data(direct_pointers)?,
        }

        let mut group = self.groups[group_index as usize].to_owned();

        {
            // Release index bitmap
            group.release_one(bitmap_index);
        }

        // Save group
        self.save_group(group, group_index)?;

        Ok(())
    }
}

#[derive(Serialize, Deserialize, Debug)]
pub struct Superblock {
    magic: [u8; 7],  // Magic number to check
    fs_version: u32, // FS Version
    // test_bytes: [u8; 20], // Secret test bytes
    block_size: u32,  // Block size in bytes
    group_count: u32, // Total groups count
    block_count: u32, // Total blocks count
    free_blocks: u32, // Available blocks
    file_count: u32,  // File count in fs
    created: u64,     // FS creation time
    modified: u64,    // FS last modification time
    checksum: u32,    // Superblock checksum
}

impl Superblock {
    fn new() -> Self {
        Self {
            magic: MAGIC,
            fs_version: FS_VERSION,
            block_size: BLOCK_SIZE,
            group_count: 0,
            block_count: 1,
            free_blocks: 0,
            file_count: 0,
            created: now(),
            modified: now(),
            checksum: 0,
        }
    }

    pub fn update_modified(&mut self) {
        self.modified = now();
    }

    #[allow(dead_code)]
    pub fn serialize(&mut self) -> anyhow::Result<Vec<u8>> {
        self.checksum();
        bincode::serialize(self).map_err(|e| e.into())
    }

    #[inline]
    pub fn serialize_into<W>(&mut self, w: W) -> anyhow::Result<()>
    where
        W: Write,
    {
        self.checksum();
        bincode::serialize_into(w, self).map_err(|e| e.into())
    }

    #[inline]
    pub fn deserialize_from<R>(r: R) -> anyhow::Result<Self>
    where
        R: Read,
    {
        let mut sb: Self = bincode::deserialize_from(r)?;
        if !sb.verify_checksum() {
            return Err(anyhow!("Superblock checksum verification failed"));
        }

        Ok(sb)
    }

    #[inline]
    fn checksum(&mut self) {
        self.checksum = 0;
        self.checksum = calculate_checksum(&self);
    }

    #[inline]
    fn verify_checksum(&mut self) -> bool {
        let checksum = self.checksum;
        self.checksum = 0;
        let ok = checksum == calculate_checksum(&self);
        self.checksum = checksum;

        ok
    }
}

#[derive(Debug, Default, Clone)]
pub struct Group {
    pub block_bitmap: BitVec<u8, Lsb0>,
}

impl Group {
    fn new(block_bitmap: BitVec<u8, Lsb0>) -> Self {
        Self { block_bitmap }
    }

    pub fn init() -> Self {
        let mut block_bitmap = BitVec::<u8, Lsb0>::with_capacity(BLOCK_SIZE as usize * 8);
        block_bitmap.resize(BLOCK_SIZE as usize * 8, false);
        Self { block_bitmap }
    }

    #[inline]
    fn seek_position(group_index: u32) -> u32 {
        // Superblock BLOCK_SIZE (4kib)
        // + Group ID * (BLOCK_SIZE + BLOCKS_PER_GROUP * BLOCK_SIZE)
        BLOCK_SIZE + (group_index * (BLOCK_SIZE + BLOCKS_PER_GROUP * BLOCK_SIZE))
    }

    #[inline]
    pub fn create_public_address(group_index: u32, bitmap_index: u32) -> u32 {
        // Maybe +1?
        Self::seek_position(group_index) / BLOCK_SIZE + bitmap_index + 1
    }

    /// Returns (group_index, bitmap_index)
    #[inline]
    pub fn translate_public_address(mut block_index: u32) -> (u32, u32) {
        block_index -= 1;
        let n = BLOCKS_PER_GROUP + 1;
        let group_index = (block_index as u32) / n;
        let bitmap_index = if group_index == 0 {
            block_index - 1
        } else {
            block_index % (group_index * n) - 1
        };
        (group_index, bitmap_index)
    }

    #[inline]
    pub fn serialize_into<W>(&self, mut w: W) -> anyhow::Result<()>
    where
        W: Write + Seek,
    {
        w.write_all(self.block_bitmap.as_raw_slice())?;

        Ok(())
    }

    #[inline]
    pub fn deserialize_from<R>(mut r: R, group_index: u32) -> anyhow::Result<Group>
    where
        R: Read + Seek,
    {
        let mut buf = Vec::with_capacity(BLOCK_SIZE as usize);
        unsafe {
            buf.set_len(BLOCK_SIZE as usize);
        }

        let offset = Self::seek_position(group_index);
        r.seek(SeekFrom::Start(offset as u64))?;
        r.read_exact(&mut buf)?;
        let data_bitmap = BitVec::<u8, Lsb0>::from_slice(&buf);

        Ok(Group::new(data_bitmap))
    }

    // #[inline]
    // pub fn has_data_block(&self, i: usize) -> bool {
    //     self.block_bitmap.get(i - 1).as_deref().unwrap_or(&false) == &true
    // }

    #[inline]
    pub fn free_data_blocks(&self) -> usize {
        self.block_bitmap.count_zeros()
    }

    #[inline]
    pub fn total_data_blocks(&self) -> usize {
        self.block_bitmap.len()
    }

    #[inline]
    fn release_one(&mut self, bitmap_index: u32) {
        self.block_bitmap.set(bitmap_index as usize, false);
    }

    #[inline]
    pub fn release_data_region(&mut self, bitmap_index: u32, length: u32) {
        for i in bitmap_index..(bitmap_index + length) {
            self.block_bitmap.set(i as usize, false);
        }
    }

    /// Set bitmap index by force
    #[inline]
    fn force_allocate_at(&mut self, bitmap_index: u32) {
        // Set it to be taken
        self.block_bitmap.set(bitmap_index as usize, true);
    }

    /// Allocate one block
    #[inline]
    fn allocate_one(&mut self, group_index: u32) -> Option<u32> {
        // If we have at least one free block index
        if let Some(bitmap_index) = self.block_bitmap.iter_zeros().next() {
            // Set it to be taken
            self.block_bitmap.set(bitmap_index, true);
            // Return index as public address
            return Some(Self::create_public_address(
                group_index,
                bitmap_index as u32,
            ));
        }
        None
    }

    /// Allocate data region
    #[inline]
    fn allocate_region(
        &mut self,
        // to translate internal ID into public address
        group_index: u32,
        // Blocks to allocate
        mut blocks_to_allocate: usize,
        // Maximum number of region to allocate
        max_regions: usize,
    ) -> (Vec<(u32, u32)>, usize) {
        let mut regions = Vec::new();
        let mut region: Option<(u32, u32)> = None;

        let mut iter = self.block_bitmap.iter_mut().enumerate().peekable();

        while let Some((bitmap_index, mut i)) = iter.next() {
            // Break loop if we dont need more blocks
            // to allocate
            if blocks_to_allocate == 0 {
                // Add opened region to regions if we have one opened
                if let Some(r) = region.take() {
                    regions.push(r);
                }
                break;
            }

            // If current block index is free
            if !*i {
                // If we have opened region
                if let Some((_block_index, region_length)) = region.as_mut() {
                    // Then increment region_length
                    *region_length += 1;
                } else {
                    // Else we need to create a new opened region
                    region = Some((
                        Self::create_public_address(group_index, bitmap_index as u32),
                        1,
                    ));
                }

                // Decrease blocks number to allocate by one
                // As we allocate on in this if block
                blocks_to_allocate -= 1;

                // Set block index as taken
                i.set(true);

                // If i is taken
            } else {
                // Check if we have opened region
                // and close it
                if let Some(r) = region.take() {
                    regions.push(r);

                    // Break loop if we reached the maximum region number
                    // we dont have room to allocate more regions
                    if regions.len() == max_regions {
                        break;
                    }
                }
            }

            // If last item, then clean up
            if let None = iter.peek() {
                // If we have opened region
                // then close it
                if let Some(r) = region.take() {
                    regions.push(r);
                }
            }
        }

        // allocated regions
        //  |                  remaining blocks to allocate
        //  |                     |
        (regions, blocks_to_allocate)
    }

    // #[inline]
    // fn next_free_data_region(&self, size: u32) -> Option<(usize, usize)> {
    //     self.block_bitmap
    //         .windows(size as usize)
    //         .position(|p| p.not_any())
    //         .map(|p| (p + 1, p + size as usize + 1))
    // }
}

#[derive(Serialize, Deserialize, Debug)]
pub struct Inode {
    pub block_index: u32,
    pub created: u64,
    pub last_modified: u64,
    pub size: u64,
    pub data_checksum: u32,
    pub data: Data,
}

#[derive(Serialize, Deserialize, Debug)]
pub enum Data {
    Raw(Vec<u8>),
    DirectPointers(Vec<(u32, u32)>),
}

impl Default for Data {
    fn default() -> Self {
        Self::Raw(vec![])
    }
}

impl Inode {
    pub fn new(block_index: u32) -> Self {
        Self {
            block_index,
            created: now(),
            last_modified: now(),
            size: 0,
            data_checksum: calculate_checksum(&()),
            data: Data::Raw(vec![]),
        }
    }

    #[inline]
    pub fn serialize_into<W>(&self, mut w: W) -> anyhow::Result<()>
    where
        W: Write + Seek,
    {
        // Serialize inode bytes array
        let serialized = bincode::serialize(&self)?;

        // Check if serialized inode size is correct
        assert!(serialized.len() as u32 <= BLOCK_SIZE);

        // Write serialized inode
        w.write_all(&serialized)?;

        // Flush buffer
        w.flush()?;

        Ok(())
    }

    #[inline]
    pub fn deserialize_from<R>(mut r: R) -> anyhow::Result<Self>
    where
        R: Read + Seek,
    {
        let inode: Inode = bincode::deserialize_from(&mut r)?;
        Ok(inode)
    }

    #[inline]
    fn set_last_modified(&mut self) {
        self.last_modified = now();
    }

    #[inline]
    fn set_raw_data<R>(&mut self, data: &mut R, data_size: u64) -> anyhow::Result<()>
    where
        R: Read,
    {
        let mut buffer = vec![];
        let data_len = data.read_to_end(&mut buffer)?;

        if data_len != data_size as usize {
            return Err(anyhow!("Data read and given data size are not the same"));
        }

        if data_len > INODE_CAPACITY as usize {
            return Err(anyhow!(
                "Data is too big to be raw data. Does not fit inside inode"
            ));
        }

        self.size = data_size;
        self.data = Data::Raw(buffer);
        Ok(())
    }

    #[inline]
    fn set_direct_pointers(&mut self, pointers: Vec<(u32, u32)>, data_size: u64) {
        self.data = Data::DirectPointers(pointers);
        self.size = data_size;
    }
}

#[derive(Serialize, Deserialize, Default, Debug)]
pub struct DirectoryIndex {
    directories: BTreeMap<OsString, u32>,
    checksum: u32,
}

impl DirectoryIndex {
    pub fn init() -> Self {
        let mut r = Self {
            directories: BTreeMap::new(),
            checksum: 0,
        };
        r.checksum();
        r
    }
    pub fn find_dir<P>(&self, dir: P) -> Option<&u32>
    where
        P: AsRef<Path>,
    {
        self.directories.get(dir.as_ref().as_os_str())
    }
    pub fn create_dir<P>(&mut self, dir: P, inode_index: u32) -> Option<&u32>
    where
        P: AsRef<Path>,
    {
        if self.find_dir(&dir).is_some() {
            return None;
        }
        self.directories
            .insert(dir.as_ref().as_os_str().to_os_string(), inode_index);
        self.find_dir(dir)
    }
    pub fn move_dir<P>(&mut self, from: P, to: P) -> anyhow::Result<()>
    where
        P: AsRef<Path>,
    {
        if self.find_dir(&from).is_none() {
            return Err(anyhow!("From directory not found"));
        }
        if self.find_dir(&to).is_some() {
            return Err(anyhow!("Target directory has already exist"));
        }

        let dir_inode = self.directories.remove(from.as_ref().as_os_str()).unwrap();

        let _ = self
            .directories
            .insert(to.as_ref().as_os_str().to_os_string(), dir_inode);

        Ok(())
    }
    pub fn directories(&self) -> &BTreeMap<OsString, u32> {
        &self.directories
    }
    fn checksum(&mut self) {
        self.checksum = 0;
        self.checksum = calculate_checksum(&self);
    }

    fn verify_checksum(&mut self) -> bool {
        let checksum = self.checksum;
        self.checksum = 0;
        let ok = checksum == calculate_checksum(&self);
        self.checksum = checksum;

        ok
    }
}

#[derive(Serialize, Deserialize, Debug, Default)]
pub struct Directory {
    pub files: BTreeMap<String, u32>,
    checksum: u32,
}

impl Directory {
    fn init() -> Self {
        let mut dir = Directory {
            files: BTreeMap::new(),
            checksum: 0,
        };
        dir.checksum();
        dir
    }

    pub fn get_file(&self, file_name: &str) -> Option<u32> {
        self.files.get(file_name).map(|x| *x)
    }

    pub fn add_file(&mut self, file_name: &str, inode_block_index: u32) -> anyhow::Result<()> {
        match self.get_file(file_name) {
            Some(_) => Err(anyhow!("File already exist")),
            None => {
                self.files.insert(file_name.into(), inode_block_index);
                Ok(())
            }
        }
    }

    fn remove_file(&mut self, file_name: &str) -> anyhow::Result<()> {
        match self.files.remove(file_name) {
            Some(_) => Ok(()),
            None => Err(anyhow!("File not found!")),
        }
    }

    fn checksum(&mut self) {
        self.checksum = 0;
        self.checksum = calculate_checksum(&self);
    }

    fn verify_checksum(&mut self) -> bool {
        let checksum = self.checksum;
        self.checksum = 0;
        let ok = checksum == calculate_checksum(&self);
        self.checksum = checksum;

        ok
    }
}

#[cfg(test)]
mod tests {
    // use super::*;
    // use std::io::Cursor;
    // use std::time::{self, SystemTime};

    #[test]
    fn test_block_bitmap_seek_position() {
        // let group = Group::new(0);
        // assert_eq!(group.bitmap_seek_position(), BLOCK_SIZE);

        // let group = Group::new(1);
        // assert_eq!(group.bitmap_seek_position(), 134_221_824);
    }
}