#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "aes.h"


void process_enc(char *seed, char *key, char *iv){
    for(int i = 0; i < strlen(seed); i++)
    {
        key[i] ^= seed[i];
        iv[i] ^= seed[i];
    }
}
void process_file(FILE *fp, char *key, char is_encrypt){
    struct AES_ctx ctx;
    char enc_key[32] = {0};
    char enc_iv[16] = {0};
    char buf[256] = {0};
    process_enc(key,enc_key,enc_iv);
    AES_init_ctx_iv(&ctx,enc_key,enc_iv);
    FILE *op = fopen("result", "wb");
    size_t bytes_read = 0;
    do{      
        if(is_encrypt & 1 > 0){
            is_encrypt += 3;
            continue;  
        }
        AES_CTR_xcrypt_buffer(&ctx, buf, 256);
        if(is_encrypt == 2){
            is_encrypt = 0;
            continue;
        }
        fwrite(buf, 1, 256, op);
        memset(buf, 0, sizeof(buf));
    }while((bytes_read = fread(buf, 1, 256, fp)) > 0);
    

}

int main(int argc, char **argv){
    srand(time(NULL));
    if(argc != 4 || strcmp(argv[1], "encrypt") && strcmp(argv[1], "decrypt")){
        printf("Usage:\n");
        printf("./safe_packer decrypt file key - decrypts file with provided key\n");
        printf("./safe_packer encrypt file key - encrypts file with provided key\n");
        return 1;
    }
    FILE *fp;
    fp = fopen(argv[2], "rb");
    if(fp == NULL){
        printf("File error!\n");
        return 1;
    }
    process_file(fp, argv[3], (strcmp(argv[1], "encrypt")));
    fclose(fp);
    return 0;
}