// File: /workspace/github_c_makefile_star2_O2/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 $0x68, %rsp
cmpl $0x3, %edi
jne 0x21df
movq %rsi, %rbx
movq 0x8(%rsi), %rdi
pushq $0x2
popq %rsi
xorl %eax, %eax
callq 0x10e0
movq %rbx, -0x30(%rbp)
movq 0x10(%rbx), %r15
pushq $0x3
popq %rdx
pushq $0x1
popq %rcx
movl $0x20000, %esi          # imm = 0x20000
xorl %edi, %edi
movl %eax, %r8d
xorl %r9d, %r9d
callq 0x1080
movq %rax, 0x33c6(%rip)      # 0x50b0
cmpq $-0x1, %rax
je 0x21fd
movq %rax, %rbx
movzwl 0x45e(%rax), %r14d
shll $0x5, %r14d
movq %r15, %rdi
callq 0x1120
movq %rax, %r13
movq %r15, %rdi
callq 0x1120
movq %rax, %r15
movq %r13, %rdi
callq 0x10a0
movq %rax, %r12
movq %r15, %rdi
callq 0x10c0
movq %rax, %r15
movq 0x337a(%rip), %rdi      # 0x50b0
movl 0x808(%rbx,%r14), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x15e2
movq %r13, %rdi
movq %rax, %rsi
movq %r15, %rdx
callq 0x12d7
testl %eax, %eax
je 0x1fd3
movq 0x334b(%rip), %rdi      # 0x50b0
movl 0x808(%rbx,%r14), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x15e2
movq %r12, %rdi
movq %rax, %rsi
callq 0x130d
shrq $0x20, %rax
cmpq $0xb, %rax
setae %cl
cmpq $0x2, %rax
sete %al
orb %cl, %al
je 0x1fe8
movq %r14, %r15
movq %r12, %r13
movq -0x30(%rbp), %r12
movq 0x10(%r12), %r14
movq 0x32fe(%rip), %rdi      # 0x50b0
movl 0x808(%rbx,%r15), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x15e2
movq %r14, %rdi
movq %rax, %rsi
callq 0x130d
movq %rax, %r14
cmpb $0x64, %r14b
je 0x2008
shrq $0x20, %r14
movq 0x32c9(%rip), %rdi      # 0x50b0
movl 0x808(%rbx,%r15), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x15e2
movq %rax, %rdi
movq %r14, -0x60(%rbp)
movl %r14d, %esi
callq 0x15d2
movq %rax, -0x78(%rbp)
movq 0x329d(%rip), %rdi      # 0x50b0
movl 0x808(%rbx,%r15), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x15e2
movq %r13, %rdi
movq %rax, %rsi
callq 0x130d
movq %rax, %r14
shrq $0x20, %r14
movq 0x10(%r12), %rdi
callq 0x1ac9
movq %rax, -0x80(%rbp)
movq 0x3264(%rip), %rdi      # 0x50b0
movq %rbx, -0x50(%rbp)
movq %r15, -0x48(%rbp)
movl 0x808(%rbx,%r15), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x15e2
movq %rax, -0x68(%rbp)
movq %rax, %rdi
movq %r14, -0x70(%rbp)
movl %r14d, %esi
callq 0x15d2
movq %rax, %rbx
movl 0x28(%rax), %esi
movq 0x322a(%rip), %rdi      # 0x50b0
movl $0x400, %edx            # imm = 0x400
callq 0x15e2
movq %rax, -0x30(%rbp)
xorl %r14d, %r14d
movq $0x0, -0x58(%rbp)
movq %rbx, -0x38(%rbp)
movl 0x4(%rbx), %r13d
xorl %r12d, %r12d
movq -0x80(%rbp), %rbx
movl %r13d, -0x3c(%rbp)
cmpl %r13d, %r14d
jae 0x2140
movq %r12, -0x88(%rbp)
movl %r14d, %r15d
andl $0x3ff, %r15d           # imm = 0x3FF
movq -0x30(%rbp), %r12
leaq (%r12,%r15), %r13
movq %rbx, %rdi
callq 0x1070
movzbl 0x6(%r12,%r15), %ecx
movq %r13, %r12
cmpq %rcx, %rax
jne 0x1efe
leaq 0x8(%r12), %rsi
movq %rbx, %rdi
movq %rax, %rdx
callq 0x1060
testl %eax, %eax
je 0x1f42
movzwl 0x4(%r12), %eax
addl %eax, %r14d
movl -0x3c(%rbp), %r13d
cmpl %r13d, %r14d
setae %al
testw $0x3ff, %r14w           # imm = 0x3FF
setne %cl
orb %al, %cl
jne 0x1eb2
movq -0x58(%rbp), %rdx
incl %edx
movq -0x68(%rbp), %rdi
movq -0x70(%rbp), %rsi
movq %rdx, -0x58(%rbp)
callq 0x1617
movq %rax, -0x30(%rbp)
movq -0x38(%rbp), %rbx
jmp 0x1ea3
movzwl 0x4(%r12), %r15d
movq -0x88(%rbp), %rax
testq %rax, %rax
je 0x1f5e
addw %r15w, 0x4(%rax)
jmp 0x2140
cmpl $0x400, %r15d           # imm = 0x400
jne 0x202c
movl -0x3c(%rbp), %r12d
decl %r12d
movl %r12d, %r13d
shrl $0xa, %r12d
movq 0x3130(%rip), %rdi      # 0x50b0
movq -0x58(%rbp), %rbx
cmpl $0xb, %ebx
ja 0x2057
movq -0x50(%rbp), %r14
movl %r12d, -0x30(%rbp)
movq -0x48(%rbp), %r12
movl 0x800(%r14,%r12), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x15e2
movl %ebx, %r15d
movq -0x38(%rbp), %rcx
movl 0x28(%rcx,%r15,4), %esi
decl %esi
movq %rax, %rdi
callq 0x17ee
incw 0x80c(%r14,%r12)
movl -0x30(%rbp), %r12d
jmp 0x209f
movq 0x301e(%rip), %rax      # 0x4ff8
movq (%rax), %rcx
leaq 0x10bc(%rip), %rdi      # 0x30a0
pushq $0x18
jmp 0x1ffb
movq 0x3009(%rip), %rax      # 0x4ff8
movq (%rax), %rcx
leaq 0x10c0(%rip), %rdi      # 0x30b9
pushq $0x13
popq %rsi
pushq $0x1
popq %rdx
callq 0x1110
pushq $0x2
jmp 0x2026
movq 0x2fe9(%rip), %rax      # 0x4ff8
movq (%rax), %rcx
leaq 0x10b4(%rip), %rdi      # 0x30cd
pushq $0x1b
popq %rsi
pushq $0x1
popq %rdx
callq 0x1110
pushq $0x15
popq %rbx
jmp 0x21ce
addl %r15d, %r14d
andl $0x3ff, %r14d           # imm = 0x3FF
movq -0x30(%rbp), %rax
leaq (%rax,%r14), %rsi
movzwl 0x4(%rax,%r14), %edx
movq %r12, %rdi
callq 0x10b0
addw %r15w, 0x4(%r12)
jmp 0x2140
movq -0x38(%rbp), %rax
movl 0x58(%rax), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x15e2
movq %rax, %r14
movq 0x303e(%rip), %rdi      # 0x50b0
movq -0x50(%rbp), %rax
movq -0x48(%rbp), %rcx
movl 0x800(%rax,%rcx), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x15e2
leal -0xc(%rbx), %ecx
movl (%r14,%rcx,4), %esi
decl %esi
movq %rax, %rdi
callq 0x17ee
movl %ebx, %r15d
movl %r12d, %r12d
movq -0x38(%rbp), %rbx
cmpq %r12, %r15
jae 0x2131
cmpq $0xb, %r15
jne 0x210d
movq 0x2ff4(%rip), %rdi      # 0x50b0
movl 0x58(%rbx), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x15e2
movq %rax, %r14
movl (%rax), %eax
movl %eax, 0x54(%rbx)
cmpl $0x3400, %r13d          # imm = 0x3400
jb 0x2129
movq 0x2fcf(%rip), %rdi      # 0x50b0
movq -0x50(%rbp), %rax
movq -0x48(%rbp), %rcx
movl 0x800(%rax,%rcx), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x15e2
movl 0x58(%rbx), %esi
decl %esi
movq %rax, %rdi
callq 0x17ee
addl $-0x2, 0x1c(%rbx)
jmp 0x2129
jbe 0x211b
movl -0x2c(%r14,%r15,4), %eax
movl %eax, -0x30(%r14,%r15,4)
jmp 0x2129
movq -0x38(%rbp), %rcx
movl 0x2c(%rcx,%r15,4), %eax
movl %eax, 0x28(%rcx,%r15,4)
incq %r15
jmp 0x20a6
movq -0x38(%rbp), %rax
addl $0xfffffc00, 0x4(%rax)  # imm = 0xFFFFFC00
addl $-0x2, 0x1c(%rax)
movq 0x2f69(%rip), %rdi      # 0x50b0
movq -0x50(%rbp), %rbx
movq -0x48(%rbp), %r12
movl 0x800(%rbx,%r12), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x15e2
movq %rax, %r14
movq 0x2f45(%rip), %rdi      # 0x50b0
movl 0x804(%rbx,%r12), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x15e2
movq -0x78(%rbp), %rdi
decw 0x1a(%rdi)
jne 0x21be
movq %rax, %r15
incw 0x80e(%rbx,%r12)
movl 0x1c(%rdi), %eax
shrl %eax
addw %ax, 0x80c(%rbx,%r12)
movq 0x2f08(%rip), %rsi      # 0x50b0
movq %r14, %rdx
callq 0x1bff
movq -0x60(%rbp), %rsi
decl %esi
movq %r15, %rdi
callq 0x17ee
leaq 0xf24(%rip), %rdi       # 0x30e9
xorl %ebx, %ebx
xorl %eax, %eax
callq 0x1090
movl %ebx, %eax
addq $0x68, %rsp
popq %rbx
popq %r12
popq %r13
popq %r14
popq %r15
popq %rbp
retq
movq 0x2e12(%rip), %rax      # 0x4ff8
movq (%rax), %rcx
leaq 0xe6f(%rip), %rdi       # 0x305f
pushq $0x3b
popq %rsi
pushq $0x1
popq %rdx
callq 0x1110
jmp 0x2209
leaq 0xe97(%rip), %rdi       # 0x309b
callq 0x10f0
pushq $0x1
popq %rdi
callq 0x1100