--Copyright Cheat Engine 2023

function hookSpeedFunctions()
  --printf("mac speedhack init")
  outputDebugString('compiling macspeedhack.c')
  r,e=compile('#include <macspeedhack.c>')
  outputDebugString('done compiling')
  if r then
    createSymbolList(r,'speedhack')
    
    outputDebugString('generating hooks')
    --hook the functions that need to be hooked. Look at the settings which api's to detour
    
    local isRosetta=targetIsRosetta()
    local wasDebugged=debug_isDebugging()
    
    if isRosetta and (not wasDebugged) then
      debugProcess()
    end
    
    autoAssemble(generateAPIHookScript('gettimeofday', 'newgettimeofday', 'oldgettimeofday'))
    autoAssemble(generateAPIHookScript('libsystem_kernel.dylib.mach_absolute_time', 'newmach_absolute_time', 'oldmach_absolute_time'))
    outputDebugString('after generating hooks')
    if isRosetta and (not wasDebugged) then
      detachIfPossible()
    end
    return true
  else
    return false, e
  end

  return r
end



registerSpeedhackCallbacks(function() --OnActivate
  if (not isConnectedToCEServer()) then
    local result, errormsg
    if getAddressSafe("newgettimeofday",false,true)==nil then
      result,errormsg=hookSpeedFunctions()
    else
      result=true
    end
        
    return true, result, errormsg
  else
    return true, false, 'Not yet supported'
  end
end,

function(speed) --OnSetSpeed(speed)
  if (not isConnectedToCEServer()) then
    local result, errormsg
    outputDebugString('checking if speedhack is active')
    if (getAddressSafe("newgettimeofday",false,true)==nil) or (getAddressSafe("speedhack_wantedspeed",false,true)==nil) then
      outputDebugString('nope. Injecting speedhack code')
      result,errormsg=hookSpeedFunctions()
      if not result then return true, false, errormsg end
    end

    writeFloat("speedhack_wantedspeed", speed)
    result=true
    
    return true, true
  else
    return true, false, 'Not yet supported'
  end
end)
