#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/sha.h>

void usage() {

    printf("Usage: ./nyufile disk <options>\n"
        "  -i                     Print the file system information.\n"
        "  -l                     List the root directory.\n"
        "  -r filename [-s sha1]  Recover a contiguous file.\n"
        "  -R filename -s sha1    Recover a possibly non-contiguous file.\n");
    exit(0);

}

int hashMatch(unsigned char *SHA1hash, char *dumpedResult) {

    int hashMatch = 1;
    char *hexdump = malloc(sizeof(char) * 3);
    for (int p = 0; p < SHA_DIGEST_LENGTH; p ++) {
        sprintf(hexdump, "%02x", SHA1hash[p]);
        if (hexdump[0] != dumpedResult[2 * p] || hexdump[1] != dumpedResult[2 * p + 1]) {
            hashMatch = 0;
            break;
        }
    }
    free(hexdump);
    return hashMatch;

}

void permuteHelper(unsigned int *array, int end, int length, int size, unsigned int **permutations) {

    /* Reached the end of the array, append result */
    static int count;
    if (end == 0) {
        //printf("[LOG] ");
        permutations[count] = malloc(sizeof(unsigned int) * size);
        memcpy(permutations[count ++], array + length, sizeof(unsigned int) * size);
        return;
    }
    /* Recursive step */
    unsigned int temp;
    for (int i = 0; i < length; i ++) {
        /* Swap the start with the end */
        temp = array[i];
        array[i] = array[length - 1];
        array[length - 1] = temp;
        permuteHelper(array, end - 1, length - 1, size, permutations);
        /* Backtrack the unswapped version */
        temp = array[i];
        array[i] = array[length - 1];
        array[length - 1] = temp;
    }

}

unsigned int **permute(unsigned int *array, int length, int size) {

    /* Count the number of possible permutations */
    int totalPermutations = 1;
    for (int i = 0; i < size; i ++) totalPermutations *= length - i;

    /* Call the permutation helper function */
    unsigned int **permutations = malloc(sizeof(unsigned int *) * totalPermutations);
    permuteHelper(array, size, length, size, permutations);
    return permutations;

}

