/*
Copyright (c) 2012, OpenEmu Team
Copyright (c) 2020, Rupert Carmichael

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
  copyright notice, this list of conditions and the following disclaimer
  in the documentation and/or other materials provided with the
  distribution.
* Neither the names of the copyright holders nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
#include <regex>
#include <cstdint>
#include <cstring>

#include "serial.h"

void SerialReader::read(std::string& serial, const char *filename) {
    std::string ext = filename;
    std::string fullpath = filename;

    std::transform(ext.begin(), ext.end(), ext.begin(), tolower);

    std::string path = fullpath.substr(0, fullpath.find_last_of("/") + 1);
    ext = ext.substr(ext.find_last_of(".") + 1);

    if (ext == "cue") {
        std::ifstream cuefile(fullpath);
        std::string line;

        while (std::getline(cuefile, line)) {
            if (line.find("FILE") == std::string::npos) // Did not find "FILE"
                continue;

            cuefile.close();

            line = line.substr(line.find_first_of("\"") + 1);
            line = line.substr(0, line.find_last_of("\""));

            std::string binfile = path + line;
            serial = readbin(binfile);
            break;
        }
    }
    else if (ext == "m3u") { // Recursive call on the first cue
        std::ifstream m3ufile(fullpath);
        std::string line;
        while (std::getline(m3ufile, line)) {
            if (line.find(".cue") == std::string::npos &&
                line.find(".CUE") == std::string::npos) // Did not find .cue
                continue;

            m3ufile.close();

            std::string cuefile = path + line;
            read(serial, cuefile.c_str());
            break;
        }
    }
}

std::string SerialReaderPSX::readbin(std::string filename) {
    // Check if it's MODE1 or MODE2
    char m1buf[6] = {0}; // MODE1 Buffer
    char m2buf[6] = {0}; // MODE2 Buffer

    int sectorsize = 0, sectorheader = 0, discoffset = 0;

    std::ifstream binfile(filename);

    binfile.seekg(0x8001, std::ios::beg);
    binfile.read(m1buf, 5);

    binfile.seekg(0x9319, std::ios::beg);
    binfile.read(m2buf, 5);

    if ((std::string)m1buf == "CD001") { // ISO9660/MODE1/2048
        sectorsize = 2048; // 0x800
        sectorheader = 0;
        discoffset = ((sectorsize * 16) + sectorheader);
    }
    else if ((std::string)m2buf == "CD001") { // ISO9660/MODE2/FORM1/2352
        sectorsize = 2352; // 0x939
        sectorheader = 24; // 0x18
        discoffset = ((sectorsize * 16) + sectorheader);
    }
    else { // Invalid file
        binfile.close();
        return "";
    }

    uint64_t rootoffset = 0x9e;
    char rootrecbuf[8];

    binfile.seekg(discoffset + rootoffset, std::ios::beg);
    binfile.read(rootrecbuf, 8);

    uint64_t rootrecsector = *(uint64_t*)rootrecbuf;

    int rootrecoffset = rootrecsector * sectorsize;
    binfile.seekg(rootrecoffset, std::ios::beg);

    // Find SYSTEM.CNF
    bool foundidfile = false;
    uint64_t position = 0;
    char syscnfstr[11] = {0};

    while (position < sectorsize) {
        binfile.read(syscnfstr, 10);

        if((std::string)syscnfstr == "SYSTEM.CNF") {
            foundidfile = true;
            break;
        }

        position++;
        binfile.seekg(rootrecoffset + position, std::ios::beg);
    }

    if (!foundidfile) {
        binfile.close();
        return "";
    }
    else {
        // SYSTEM.CNF Location
        uint64_t systemcnfoffset = (rootrecoffset + position) - 0x1f;
        char systemcnflocdata[9] = {0};
        binfile.seekg(systemcnfoffset, std::ios::beg);
        binfile.read(systemcnflocdata, 8);

        uint64_t sizeextentoffset = *(uint64_t*)systemcnflocdata;
        int extentoffset = sizeextentoffset * sectorsize;

        // Data length
        int systemcnfdatalenoffset = (rootrecoffset + position) - 0x17;

        char systemcnfdatalenbuf[9] = {0};
        binfile.seekg(systemcnfdatalenoffset, std::ios::beg);
        binfile.read(systemcnfdatalenbuf, 8);

        uint64_t systemcnfdatalen = *(uint64_t*)systemcnfdatalenbuf;
        int datalen = (int)systemcnfdatalen;

        char titleIDFileExtendDataBuffer[datalen];
        binfile.seekg(extentoffset + sectorheader, std::ios::beg);
        binfile.read(titleIDFileExtendDataBuffer, datalen);

        // Search for serial string using regex
        std::regex regexp(R"(BOOT\s*=\s*?cdrom:\\?(.+\\)?(.+?(?=;|\s)))");
        std::smatch m;
        std::string output = titleIDFileExtendDataBuffer;
        std::regex_search(output, m, regexp);

        // Only use Group 2
        output = m.str(2);

        // Remove bad characters
        char badchars[] = ".:";
        for (int i = 0; i < strlen(badchars); i++) {
            output.erase(std::remove(output.begin(), output.end(), badchars[i]),
                output.end());
        }

        // Replace any underscores with dashes
        std::replace(output.begin(), output.end(), '_', '-');

        // Convert everything to upper case
        std::transform(output.begin(), output.end(), output.begin(), toupper);

        binfile.close();
        return output;
    }

    binfile.close();
    return "";
}

bool SerialReaderPSX::sbi_exists(const char *filename) {
    std::string ext = filename;
    std::string fullpath = filename;
    std::string path = fullpath.substr(0, fullpath.find_last_of("/") + 1);
    std::transform(ext.begin(), ext.end(), ext.begin(), tolower);
    ext = ext.substr(ext.find_last_of(".") + 1);

    if (ext == "cue") {
        fullpath = fullpath.substr(0, fullpath.find_last_of(".")) + ".sbi";
        std::ifstream sbifile(fullpath);
        return sbifile.good();
    }
    else if (ext == "m3u") { // Recursive call on the first cue
        std::ifstream m3ufile(filename);
        std::string line;
        bool retval = false; // Default return value in case of no .cues in .m3u

        while (std::getline(m3ufile, line)) {
            if (line.find(".cue") == std::string::npos &&
                line.find(".CUE") == std::string::npos) // Did not find .cue
                continue;

            std::string cuefile = path + line;

            if (!sbi_exists(cuefile.c_str())) {
                m3ufile.close();
                return false;
            }
            else {
                retval = true;
            }
        }
        m3ufile.close();
        return retval;
    }
    return false;
}

std::string SerialReaderSS::readbin(std::string filename) {
    // Find the start of the header
    std::ifstream binfile(filename);
    char headerbuf[0x11] = {0};
    uint32_t offset = 0x20;

    binfile.read(headerbuf, 0x10);

    if ((std::string)headerbuf != "SEGA SEGASATURN ") {
        binfile.read(headerbuf, 0x10);
        if ((std::string)headerbuf == "SEGA SEGASATURN ") {
            offset += 0x10;
        }
        else {
            binfile.close();
            return "";
        }
    }
    memset(headerbuf, 0, sizeof(headerbuf));

    // Read the serial
    binfile.seekg(offset, std::ios::beg);
    binfile.read(headerbuf, 0x0a);
    binfile.close();

    // Trim and return the serial
    std::string serial = (std::string)headerbuf;
    std::string trimchars = " \f\n\r\t\v";
    serial.erase(0, serial.find_first_not_of(trimchars));
    return serial.erase(serial.find_last_not_of(trimchars) + 1);
}
