// File: /workspace/github_c_makefile_star2_O1/Sidd0107[P]EXT2-File-System/ext2_rm.c
// Function: main
int main(int argc, char **argv) {
    //Checks valid no of argument
    if(argc != 3) {
        fprintf(stderr, "Usage: ext2_rm <image file name> <file path on ext2 image>\n");
        exit(1);
    }
    int fd = open(argv[1], O_RDWR);
    char *path = argv[2];
    //maps disk in memory
    disk = mmap(NULL, 128 * BLOCK_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if(disk == MAP_FAILED) {
        perror("mmap");
        exit(1);
    }
    struct ext2_super_block *sb = (struct ext2_super_block *)(disk + BLOCK_SIZE);
    struct ext2_group_desc *gd = (struct ext2_group_desc *)  (disk + 2*BLOCK_SIZE + ((sb -> s_block_group_nr) *  sizeof(struct ext2_group_desc)));
    
        
    char *dirc, *basec, *dirName, *pth;
    dirc = strdup(path);
    basec = strdup(path);
    pth = dirname(dirc);
    dirName = basename(basec);

    
    // Checks if file already exists and returns if yes.
    if(file_exists(dirc, get_block(disk, gd -> bg_inode_table, BLOCK_SIZE), dirName)==0){
        fprintf(stderr, "rm: File does not exist\n");
        return ENOENT;
    }
    //Getting info to check that destination is a directory and not reserved
    struct basic_fileinfo file_info = find_file(pth, get_block(disk, gd -> bg_inode_table, BLOCK_SIZE));
    if(file_info.inode < 11 && file_info.inode != 2){
        fprintf(stderr, "Invalid destination");
        return ENOENT;
    }
	
	file_info = find_file(argv[2], get_block(disk, gd -> bg_inode_table, BLOCK_SIZE));
	if(file_info.type == 'd'){
        fprintf(stderr, "rm: Cant delete a directory");
        return EISDIR;
    }
    //gets inode of file to be deleted.
    int inode_num = file_info.inode;
    struct ext2_inode *current_file_inode = get_inode(get_block(disk, gd -> bg_inode_table, BLOCK_SIZE), inode_num);
    // Getting parent directory
    struct basic_fileinfo parent_info = find_file(pth, get_block(disk, gd -> bg_inode_table, BLOCK_SIZE));
    inode_num = parent_info.inode;
    char *filename = extract_filename(argv[2]);
    char *inode_base = get_block(disk, gd->bg_inode_table, BLOCK_SIZE);
	
    // Loops through the iblocks of parent directory in search for the directory
    // entry to be deleted.
    struct ext2_inode *current_inode = get_inode(inode_base, inode_num);
    unsigned int block_num = current_inode->i_block[0];
    
    unsigned int cur_index_serviced = 0, cur_inode_index = 0;
    char *current_block = get_block(disk, block_num, BLOCK_SIZE);
    struct ext2_dir_entry_2 *current = (struct ext2_dir_entry_2 *) current_block;
    struct ext2_dir_entry_2 *previous = NULL;
    while(cur_index_serviced < current_inode -> i_size){
        current = (struct ext2_dir_entry_2 *) (current_block + (cur_index_serviced % BLOCK_SIZE));
        // Checks if current entry is the one to be deleted(name match)
        if (strlen(filename) == current -> name_len && !strncmp(filename, current -> name, strlen(filename))){
		    //If there is no previous entry, two cases exist.
            if(previous==NULL){
				//If the current directory entry takes up the entire block, "free" block by unsetting the corresponding bit in bitmap.
				//and "shift" the i_block numbers down an index including the indirect blocks.
                if(current->rec_len==BLOCK_SIZE){
                    //unset block and move blocks after by 1.
                    unsigned int cur_index = cur_inode_index;
                    unsigned int blocks_used = (current_inode -> i_size > 0)? ((current_inode -> i_size - 1)/BLOCK_SIZE) + 1 : 0;
                    //Loops through all blocks coming up and shifts
					if(cur_inode_index < 12){
						unset_bit(get_block(disk, gd->bg_block_bitmap, BLOCK_SIZE), current_inode -> i_block[cur_inode_index] - 1);
						gd -> bg_free_blocks_count++;
					}
					else{
                        //Gets indirect block and unsets bit of corresponding element in that block
						unsigned int *indirect = (unsigned int*) get_block(disk, current_inode -> i_block[12], BLOCK_SIZE);
						unset_bit(get_block(disk, gd->bg_block_bitmap, BLOCK_SIZE), indirect[cur_inode_index - 12] - 1);
					}
                    //Loops through all blocks coming up
                    while(cur_index < blocks_used-1){
                        unsigned int* indirect_block;
                        //We are on the 11th iblock
                        if(cur_index==11){
                            //Implies 12th block is being used does the shift
							indirect_block = (unsigned int*)get_block(disk, current_inode->i_block[cur_index+1], BLOCK_SIZE);
                            current_inode->i_block[cur_index]=indirect_block[0];
							//if indirect block is being used
                            if(cur_index+1 < blocks_used-1){
								unset_bit(get_block(disk, gd->bg_block_bitmap, BLOCK_SIZE), current_inode -> i_block[12] - 1);
								current_inode -> i_blocks -= 2;
								//IN THIS CASE FREE THE BLOCK BY UNSETTING THE I_BLOCK[12]TH BIT IN THE BITMAP
                            }
                        }else{
                            //If entry is in indirect block complete the shift within the indirect block.
                            if(cur_index>=12){
                                indirect_block[cur_index - 12] = indirect_block[cur_index - 11];
                            }
							else{
								current_inode->i_block[cur_index] = current_inode->i_block[cur_index+1];
							}
                        }
						// Increment curr index
						cur_index++;
                    }
                    current_inode -> i_size -= BLOCK_SIZE;
                    current_inode -> i_blocks -= 2;
				}
			    else{
				    //Copy next element in place of current and increment length.
					//Setting previous to next element
					unsigned short current_reclen = current -> rec_len;
					//AND NEXT NOW REPRESENTS NEXT
					struct ext2_dir_entry_2 *next = (struct ext2_dir_entry_2 *) (current_block + ((cur_index_serviced + current -> rec_len) % BLOCK_SIZE));
					memcpy(current, next, next->rec_len); //Note previous is now the next element
					current -> rec_len += current_reclen;
                }
			}else{
                    //Not first
                    previous->rec_len += current->rec_len;
            }
			break;
        }
        //Sets the previous element to current and incremenets cur index
        previous = current;
        cur_index_serviced += current -> rec_len;
        if (cur_index_serviced < current_inode->i_size && cur_index_serviced % BLOCK_SIZE == 0){
            cur_inode_index++;
            current_block = get_block_from_inode(inode_base, inode_num, cur_inode_index);
            previous=NULL;
        }
    }
    
    //unsets all block bits
    char *bitmaprs = get_block(disk, gd->bg_block_bitmap, BLOCK_SIZE);
    char *bitmapind = get_block(disk, gd->bg_inode_bitmap, BLOCK_SIZE);
    // Decrements i_link_count to make sure it is 0 else we cant
    // unset as there is still a hard link pointing to it.
	current_file_inode -> i_links_count --;
    // unset inode(unset_bit) if no hard links and unset all block bits(free_inode helper)
	if(current_file_inode -> i_links_count == 0){
		gd -> bg_free_inodes_count++;
		gd -> bg_free_blocks_count += current_file_inode -> i_blocks / 2;
		free_inode(current_file_inode, disk, bitmaprs);
		unset_bit(bitmapind, file_info.inode - 1);
	}
	printf("File removed.");
    return 0;
    
}

// Assembly:
pushq %rbp
movq %rsp, %rbp
pushq %r15
pushq %r14
pushq %r13
pushq %r12
pushq %rbx
subq $0x58, %rsp
cmpl $0x3, %edi
jne 0x2410
movq %rsi, %rbx
movq 0x8(%rsi), %rdi
movl $0x2, %esi
xorl %eax, %eax
callq 0x10e0
movq %rbx, -0x50(%rbp)
movq 0x10(%rbx), %rbx
movl $0x20000, %esi          # imm = 0x20000
xorl %edi, %edi
movl $0x3, %edx
movl $0x1, %ecx
movl %eax, %r8d
xorl %r9d, %r9d
callq 0x1080
movq %rax, 0x3154(%rip)      # 0x50b0
cmpq $-0x1, %rax
je 0x2415
movq %rax, %r14
movzwl 0x45e(%rax), %r12d
shll $0x5, %r12d
movq %rbx, %rdi
callq 0x1120
movq %r14, %r13
movq %rax, %r15
movq %rbx, %rdi
callq 0x1120
movq %rax, %rbx
movq %r15, %rdi
callq 0x10a0
movq %rax, %r14
movq %rbx, %rdi
callq 0x10c0
movq %rax, %rbx
movq 0x3105(%rip), %rdi      # 0x50b0
movl 0x808(%r13,%r12), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x1773
movq %r15, %rdi
movq %rax, %rsi
movq %rbx, %rdx
callq 0x1402
testl %eax, %eax
je 0x2239
movq 0x30d6(%rip), %rdi      # 0x50b0
movl 0x808(%r13,%r12), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x1773
movq %r14, %rdi
movq %rax, %rsi
callq 0x1438
shrq $0x20, %rax
cmpq $0xb, %rax
setae %cl
cmpq $0x2, %rax
sete %al
orb %cl, %al
je 0x2240
movq %r13, %r15
movq -0x50(%rbp), %r13
movq 0x10(%r13), %rbx
movq 0x308d(%rip), %rdi      # 0x50b0
movl 0x808(%r15,%r12), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x1773
movq %rbx, %rdi
movq %rax, %rsi
callq 0x1438
movq %rax, %rbx
cmpb $0x64, %bl
je 0x224f
shrq $0x20, %rbx
movq 0x3059(%rip), %rdi      # 0x50b0
movl 0x808(%r15,%r12), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x1773
movq %rax, %rdi
movq %rbx, -0x60(%rbp)
movl %ebx, %esi
callq 0x1763
movq %rax, -0x68(%rbp)
movq 0x302e(%rip), %rdi      # 0x50b0
movl 0x808(%r15,%r12), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x1773
movq %r14, %rdi
movq %rax, %rsi
callq 0x1438
movq %rax, %rbx
shrq $0x20, %rbx
movq 0x10(%r13), %rdi
callq 0x1cfe
movq %rax, %r14
movq 0x2ff7(%rip), %rdi      # 0x50b0
movq %r15, -0x38(%rbp)
movq %r12, -0x40(%rbp)
movl 0x808(%r15,%r12), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x1773
movq %rax, -0x70(%rbp)
movq %rax, %rdi
movq %rbx, -0x78(%rbp)
movl %ebx, %esi
callq 0x1763
movq %rax, %r13
movl 0x28(%rax), %esi
movq 0x2fbe(%rip), %rdi      # 0x50b0
movl $0x400, %edx            # imm = 0x400
callq 0x1773
movq %rax, -0x58(%rbp)
movl 0x4(%r13), %eax
testl %eax, %eax
je 0x2371
movq %r14, %r15
xorl %ebx, %ebx
movq $0x0, -0x30(%rbp)
xorl %r12d, %r12d
movq %r13, -0x48(%rbp)
movq %rbx, -0x80(%rbp)
movl %eax, -0x50(%rbp)
movl %r12d, %r13d
andl $0x3ff, %r13d           # imm = 0x3FF
movq -0x58(%rbp), %r14
leaq (%r14,%r13), %rbx
movq %r15, %rdi
callq 0x1070
movzbl 0x6(%r14,%r13), %ecx
cmpq %rcx, %rax
jne 0x215f
leaq 0x8(%rbx), %rsi
movq %r15, %rdi
movq %rax, %rdx
callq 0x1060
testl %eax, %eax
je 0x21ae
movzwl 0x4(%rbx), %eax
addl %eax, %r12d
cmpl -0x50(%rbp), %r12d
setae %al
testl $0x3ff, %r12d           # imm = 0x3FF
setne %cl
orb %al, %cl
jne 0x2198
movq -0x30(%rbp), %rdx
incl %edx
movq -0x70(%rbp), %rdi
movq -0x78(%rbp), %rsi
movq %rdx, -0x30(%rbp)
callq 0x17a8
movq %rax, -0x58(%rbp)
xorl %ebx, %ebx
movq -0x48(%rbp), %r13
movl 0x4(%r13), %eax
cmpl %eax, %r12d
jb 0x2120
jmp 0x2371
movzwl 0x4(%rbx), %r14d
movq -0x80(%rbp), %rcx
testq %rcx, %rcx
movq -0x30(%rbp), %rax
je 0x21ca
addw %r14w, 0x4(%rcx)
jmp 0x2371
cmpl $0x400, %r14d           # imm = 0x400
jne 0x225e
movl -0x50(%rbp), %r12d
decl %r12d
movl %r12d, %r15d
shrl $0xa, %r12d
movq 0x2ec4(%rip), %rdi      # 0x50b0
movl %eax, %r14d
cmpl $0xb, %eax
movq %rax, -0x30(%rbp)
ja 0x2288
movq -0x40(%rbp), %rbx
movq -0x38(%rbp), %rax
movl 0x800(%rax,%rbx), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x1773
movq -0x48(%rbp), %r13
movl 0x28(%r13,%r14,4), %esi
decl %esi
movq %rax, %rdi
callq 0x19ad
movq -0x38(%rbp), %rax
incw 0x80c(%rax,%rbx)
jmp 0x22d1
callq 0x120e
jmp 0x2245
callq 0x11df
movl $0x2, %ebx
jmp 0x23ff
callq 0x11b0
movl $0x15, %ebx
jmp 0x23ff
addl %r14d, %r12d
andl $0x3ff, %r12d           # imm = 0x3FF
movq -0x58(%rbp), %rax
leaq (%rax,%r12), %rsi
movzwl 0x4(%rax,%r12), %edx
movq %rbx, %rdi
callq 0x10b0
addw %r14w, 0x4(%rbx)
jmp 0x2371
movq -0x48(%rbp), %r13
movl 0x58(%r13), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x1773
movq %rax, %rbx
movq 0x2e0c(%rip), %rdi      # 0x50b0
movq -0x38(%rbp), %rax
movq -0x40(%rbp), %rcx
movl 0x800(%rax,%rcx), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x1773
movq -0x30(%rbp), %rcx
addl $-0xc, %ecx
movl (%rbx,%rcx,4), %esi
decl %esi
movq %rax, %rdi
callq 0x19ad
cmpl %r12d, -0x30(%rbp)
jae 0x2364
movl %r12d, %r12d
cmpq $0xb, %r14
jne 0x2340
movq 0x2dc5(%rip), %rdi      # 0x50b0
movl 0x58(%r13), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x1773
movq %rax, %rbx
movl (%rax), %eax
movl %eax, 0x54(%r13)
cmpl $0x3400, %r15d          # imm = 0x3400
jb 0x2358
movq 0x2d9e(%rip), %rdi      # 0x50b0
movq -0x38(%rbp), %rax
movq -0x40(%rbp), %rcx
movl 0x800(%rax,%rcx), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x1773
movl 0x58(%r13), %esi
decl %esi
movq %rax, %rdi
callq 0x19ad
addl $-0x2, 0x1c(%r13)
jmp 0x2358
jbe 0x234e
movl -0x2c(%rbx,%r14,4), %eax
movl %eax, -0x30(%rbx,%r14,4)
jmp 0x2358
movl 0x2c(%r13,%r14,4), %eax
movl %eax, 0x28(%r13,%r14,4)
incq %r14
cmpq %r14, %r12
jne 0x22de
addl $0xfffffc00, 0x4(%r13)  # imm = 0xFFFFFC00
addl $-0x2, 0x1c(%r13)
movq 0x2d38(%rip), %rdi      # 0x50b0
movq -0x38(%rbp), %r15
movq -0x40(%rbp), %r12
movl 0x800(%r15,%r12), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x1773
movq %rax, %rbx
movq 0x2d14(%rip), %rdi      # 0x50b0
movl 0x804(%r15,%r12), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x1773
movq -0x68(%rbp), %rdi
decw 0x1a(%rdi)
jne 0x23ef
movq %rax, %r14
incw 0x80e(%r15,%r12)
movl 0x1c(%rdi), %eax
shrl %eax
addw %ax, 0x80c(%r15,%r12)
movq 0x2cd7(%rip), %rsi      # 0x50b0
movq %rbx, %rdx
callq 0x1e58
movq -0x60(%rbp), %rsi
decl %esi
movq %r14, %rdi
callq 0x19ad
leaq 0xd2c(%rip), %rdi       # 0x3122
xorl %ebx, %ebx
xorl %eax, %eax
callq 0x1090
movl %ebx, %eax
addq $0x58, %rsp
popq %rbx
popq %r12
popq %r13
popq %r14
popq %r15
popq %rbp
retq
callq 0x1188
callq 0x123d