#include <Windows.h>
#include <strsafe.h>
#include <shlwapi.h>
#include <stdio.h>

#include "Asar.h"

#pragma comment(lib, "shlwapi.lib")

// ==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==

static int PrintUsage(LPCSTR pszProgramName)
{
    printf("\nUsage:\n");
    printf("  %s /u <input.asar> <output_dir>\n", pszProgramName);
    printf("  %s /p <input_dir>  <output.asar>\n", pszProgramName);
    printf("  %s /v <input.asar>\n", pszProgramName);
    printf("\nDescription:\n");
    printf("  Packs, unpacks, and verifies Electron ASAR archive files.\n\n");
    printf("Commands:\n");
    printf("  /u <input.asar> <output_dir>    Extract ASAR archive to directory\n");
    printf("  /p <input_dir>  <output.asar>   Create ASAR archive from directory\n");
    printf("  /v <input.asar>                 Verify ASAR integrity (hash & blocks)\n\n");
    printf("Examples:\n");
    printf("  %s /u .\\app.asar extracted\n", pszProgramName);
    printf("  %s /p .\\extracted app.new.asar\n", pszProgramName);
    printf("  %s /v .\\app.new.asar\n", pszProgramName);
    printf("\n");

    return 1;
}


int main(int argc, char* argv[])
{
    LPCSTR  pszProgramName  = PathFindFileNameA(argv[0]);
    BOOL    bReturn         = FALSE;


    if (argc < 2 || lstrcmpiA(argv[1], "/?") == 0 || lstrcmpiA(argv[1], "-h") == 0)
        return PrintUsage(pszProgramName);

    
    if (lstrcmpiA(argv[1], "/v") == 0)
    {
        if (argc != 3)
        {
            printf("[!] Invalid Number Of Arguments For '/v'\n");
            return PrintUsage(pszProgramName);
        }

        bReturn = VerifyAsarFile(argv[2]);

        printf("[*] Code Integrity Verification:   %s\n", bReturn ? "[PASSED]" : "[FAILED]");

        return bReturn ? 0 : -1;
    }

    if (argc != 4)
    {
        printf("[!] Invalid Number Of Arguments\n");
        return PrintUsage(pszProgramName);
    }

    if (lstrcmpiA(argv[1], "/u") == 0)
    {
        if (!UnpackAsarFile(argv[2], argv[3]))
            return -1;
    }
    else if (lstrcmpiA(argv[1], "/p") == 0)
    {
        if (!PackAsarFile(argv[2], argv[3]))
            return -1;
    }
    else
    {
        printf("[!] Unknown Argument: %s\n", argv[1]);
        return PrintUsage(pszProgramName);
    }

    return 0;
}