// File: /workspace/github_c_makefile_star2_O3/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 0x239f
movq %rsi, %rbx
movq 0x8(%rsi), %rdi
movl $0x2, %esi
xorl %eax, %eax
callq 0x10e0
movq %rbx, -0x40(%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, 0x31d8(%rip)      # 0x50b0
cmpq $-0x1, %rax
je 0x23a4
movq %rax, %r15
movzwl 0x45e(%rax), %r12d
shll $0x5, %r12d
movq %rbx, %rdi
callq 0x1120
movq %rax, %r14
movq %rbx, %rdi
callq 0x1120
movq %r15, %r13
movq %rax, %r15
movq %r14, %rdi
callq 0x10a0
movq %rax, %rbx
movq %r15, %rdi
callq 0x10c0
movq %rax, %r15
movq 0x3189(%rip), %rdi      # 0x50b0
movl 0x808(%r13,%r12), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x175a
movq %r14, %rdi
movq %rax, %rsi
movq %r15, %rdx
callq 0x13e8
testl %eax, %eax
je 0x21c8
movq 0x315a(%rip), %rdi      # 0x50b0
movl 0x808(%r13,%r12), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x175a
movq %rbx, %rdi
movq %rax, %rsi
callq 0x141e
shrq $0x20, %rax
cmpq $0xb, %rax
setae %cl
cmpq $0x2, %rax
sete %al
orb %cl, %al
je 0x21cf
movq %r13, %r15
movq -0x40(%rbp), %r13
movq 0x10(%r13), %r14
movq 0x3111(%rip), %rdi      # 0x50b0
movl 0x808(%r15,%r12), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x175a
movq %r14, %rdi
movq %rax, %rsi
callq 0x141e
movq %rax, %r14
cmpb $0x64, %r14b
je 0x21de
shrq $0x20, %r14
movq 0x30dc(%rip), %rdi      # 0x50b0
movl 0x808(%r15,%r12), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x175a
movq %rax, %rdi
movq %r14, -0x60(%rbp)
movl %r14d, %esi
callq 0x174a
movq %rax, -0x68(%rbp)
movq 0x30b0(%rip), %rdi      # 0x50b0
movl 0x808(%r15,%r12), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x175a
movq %rbx, %rdi
movq %rax, %rsi
callq 0x141e
movq %rax, %rbx
shrq $0x20, %rbx
movq 0x10(%r13), %rdi
callq 0x1c85
movq %rax, %r14
movq 0x3079(%rip), %rdi      # 0x50b0
movq %r15, -0x38(%rbp)
movq %r12, -0x30(%rbp)
movl 0x808(%r15,%r12), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x175a
movq %rax, -0x70(%rbp)
movq %rax, %rdi
movq %rbx, -0x78(%rbp)
movl %ebx, %esi
callq 0x174a
movq %rax, %r13
movl 0x28(%rax), %esi
movq 0x3040(%rip), %rdi      # 0x50b0
movl $0x400, %edx            # imm = 0x400
callq 0x175a
movq %rax, -0x58(%rbp)
movl 0x4(%r13), %edx
testl %edx, %edx
je 0x2300
movq %r14, %rcx
xorl %ebx, %ebx
xorl %r12d, %r12d
xorl %r14d, %r14d
movq %r13, -0x50(%rbp)
movq %rbx, -0x80(%rbp)
movl %edx, -0x48(%rbp)
movq %r12, -0x40(%rbp)
movl %r14d, %r13d
andl $0x3ff, %r13d           # imm = 0x3FF
movq -0x58(%rbp), %r15
leaq (%r15,%r13), %rbx
movq %rcx, %r12
movq %rcx, %rdi
callq 0x1070
movzbl 0x6(%r15,%r13), %ecx
cmpq %rcx, %rax
jne 0x20df
leaq 0x8(%rbx), %rsi
movq %r12, %rdi
movq %rax, %rdx
callq 0x1060
testl %eax, %eax
je 0x213c
movq %r12, %r15
movzwl 0x4(%rbx), %eax
addl %eax, %r14d
movl -0x48(%rbp), %edx
cmpl %edx, %r14d
setae %al
testl $0x3ff, %r14d           # imm = 0x3FF
setne %cl
orb %al, %cl
jne 0x2127
movq -0x40(%rbp), %r12
incl %r12d
movq -0x70(%rbp), %rdi
movq -0x78(%rbp), %rsi
movl %r12d, %edx
callq 0x178f
movq %rax, -0x58(%rbp)
movq -0x50(%rbp), %r13
movl 0x4(%r13), %edx
xorl %ebx, %ebx
jmp 0x212b
movq -0x40(%rbp), %r12
movq %r15, %rcx
cmpl %edx, %r14d
jb 0x2099
jmp 0x2300
movzwl 0x4(%rbx), %r13d
movq -0x80(%rbp), %rax
testq %rax, %rax
je 0x2154
addw %r13w, 0x4(%rax)
jmp 0x2300
cmpl $0x400, %r13d           # imm = 0x400
jne 0x21ed
movl -0x48(%rbp), %r12d
decl %r12d
movl %r12d, %r15d
shrl $0xa, %r12d
movq 0x2f3a(%rip), %rdi      # 0x50b0
movq -0x40(%rbp), %rbx
movl %ebx, %r14d
cmpl $0xb, %ebx
movq -0x38(%rbp), %r13
ja 0x2217
movq -0x30(%rbp), %rax
movl 0x800(%r13,%rax), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x175a
movq -0x50(%rbp), %r13
movl 0x28(%r13,%r14,4), %esi
decl %esi
movq %rax, %rdi
callq 0x197b
movq -0x30(%rbp), %rax
movq -0x38(%rbp), %rcx
incw 0x80c(%rcx,%rax)
jmp 0x2261
callq 0x120e
jmp 0x21d4
callq 0x11df
movl $0x2, %ebx
jmp 0x238e
callq 0x11b0
movl $0x15, %ebx
jmp 0x238e
addl %r13d, %r14d
andl $0x3ff, %r14d           # imm = 0x3FF
movq -0x58(%rbp), %rax
leaq (%rax,%r14), %rsi
movzwl 0x4(%rax,%r14), %edx
movq %rbx, %rdi
callq 0x10b0
addw %r13w, 0x4(%rbx)
jmp 0x2300
movq -0x50(%rbp), %r13
movl 0x58(%r13), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x175a
movq %rax, -0x48(%rbp)
movq 0x2e7c(%rip), %rdi      # 0x50b0
movq -0x30(%rbp), %rax
movq -0x38(%rbp), %rcx
movl 0x800(%rcx,%rax), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x175a
leal -0xc(%rbx), %ecx
movq -0x48(%rbp), %rdx
movl (%rdx,%rcx,4), %esi
decl %esi
movq %rax, %rdi
callq 0x197b
cmpl %r12d, %ebx
jae 0x22f3
movl %r12d, %r12d
cmpq $0xb, %r14
jne 0x22cf
movq 0x2e36(%rip), %rdi      # 0x50b0
movl 0x58(%r13), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x175a
movq %rax, %rbx
movl (%rax), %eax
movl %eax, 0x54(%r13)
cmpl $0x3400, %r15d          # imm = 0x3400
jb 0x22e7
movq 0x2e0f(%rip), %rdi      # 0x50b0
movq -0x30(%rbp), %rax
movq -0x38(%rbp), %rcx
movl 0x800(%rcx,%rax), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x175a
movl 0x58(%r13), %esi
decl %esi
movq %rax, %rdi
callq 0x197b
addl $-0x2, 0x1c(%r13)
jmp 0x22e7
jbe 0x22dd
movl -0x2c(%rbx,%r14,4), %eax
movl %eax, -0x30(%rbx,%r14,4)
jmp 0x22e7
movl 0x2c(%r13,%r14,4), %eax
movl %eax, 0x28(%r13,%r14,4)
incq %r14
cmpq %r14, %r12
jne 0x226d
addl $0xfffffc00, 0x4(%r13)  # imm = 0xFFFFFC00
addl $-0x2, 0x1c(%r13)
movq 0x2da9(%rip), %rdi      # 0x50b0
movq -0x38(%rbp), %r15
movq -0x30(%rbp), %r12
movl 0x800(%r15,%r12), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x175a
movq %rax, %rbx
movq 0x2d85(%rip), %rdi      # 0x50b0
movl 0x804(%r15,%r12), %esi
movl $0x400, %edx            # imm = 0x400
callq 0x175a
movq -0x68(%rbp), %rdi
decw 0x1a(%rdi)
jne 0x237e
movq %rax, %r14
incw 0x80e(%r15,%r12)
movl 0x1c(%rdi), %eax
shrl %eax
addw %ax, 0x80c(%r15,%r12)
movq 0x2d48(%rip), %rsi      # 0x50b0
movq %rbx, %rdx
callq 0x1de3
movq -0x60(%rbp), %rsi
decl %esi
movq %r14, %rdi
callq 0x197b
leaq 0xd9d(%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