--[[      gtHost       ]]--
--[[      by Dog       ]]--
--[[ aka HydrantHunter ]]--
--[[ pastebin WzrdKVxm ]]--
local gtHver = "1.1.17"
--[[
Tested with/requires:
  - Mincraft 1.6.4 or 1.7.10
  - ComputerCraft 1.63+
    - A Wireless Turtle (standard or advanced)
    - gtRemote running on an Advanced Wireless Pocket Computer
]]--
local tArgs = { ... }
-- CONFIGURATION
-- Default Settings
local termX, termY = term.getSize()
local me = os.getComputerID()
local config = "/data/gtHostCnf"
local gtSettings = {
                     name = "gtHost",
                     note = "short note",
                     color = "I",
                     password = false,
                     newColors = true,
                   }
local loc = { x = "No GPS Fix", y = "No GPS Fix", z = "No GPS Fix", }
local gtInventory = { }
local newCmdData = { }
local netSide = "none"
local quit = "NO"
local client, doAction
local up, down, forward = false, false, false
local benzina, briquettes, fuelPercent, selectedSlot = 0, 0, 0, 1
local lockState, fuelState, dirCheck, gtRedstone, gtSuccess = false, false, false, false, false
 -- Color Definitions
local white = colors.white
local black = colors.black
local silver = colors.lightGray
local gray = colors.gray
local brown = colors.brown
local yellow = colors.yellow
local orange = colors.orange
local red = colors.red
local magenta = colors.magenta
local purple = colors.purple
local blue = colors.blue
local sky = colors.lightBlue
local cyan = colors.cyan
local lime = colors.lime
local green = colors.green
if not term.isColor() then
  silver = colors.white
  gray = colors.black
  brown = colors.white
  yellow = colors.white
  orange = colors.white
  red = colors.white
  magenta = colors.white
  purple = colors.white
  green = colors.white
  blue = colors.black
  sky = colors.white
  cyan = colors.white
  lime = colors.white
  green = colors.white
end
-- END CONFIGURATION
 
local function saveData()
  if not fs.exists("/data") then fs.makeDir("/data") end
  local turtleConfig = fs.open(config, "w") or error("saveData(): Cannot open " .. config .. " for writing", 0)
  turtleConfig.write(textutils.serialize(gtSettings))
  turtleConfig.close()
end
 
local function reportStatus()
  local tempSettings = {
                         program = "gtRemoteHost",
                         cc = me,
                         name = gtSettings.name,
                         note = gtSettings.note,
                         color = gtSettings.color,
                         redstone = gtRedstone,
                         lockState = lockState,
                         fuelState = fuelState,
                         fuelAmount = benzina,
                         fuelPercent = fuelPercent,
                         coal = briquettes,
                         slot = selectedSlot,
                         quietCount = 0,
                         loc = { x = loc.x, y = loc.y, z = loc.z, },
                         inv = gtInventory,
                         up = up,
                         down = down,
                         forward = forward,
                         dirCheck = dirCheck,
                       }
  if not rednet.isOpen(netSide) then
    rednet.open(netSide)
    rednet.host("gtRemote", gtSettings.name)
  end
  rednet.send(client, tempSettings)
end
 
local function netReceive()
  local newCmdData = { }
  while true do
    local id, message = rednet.receive()
    if type(message) == "table" and message.program == "gtRemote" then
      client = id
      newCmdData = message
      local validActions = {
                             move = true,     -- Movement
                             atk = true,      -- Actions - attack
                             dig = true,      -- Actions - break
                             dcToggle = true, -- Toggle obstacle check
                             sCmd = true,     -- Shell command
                             put = true,      -- Action - place
                             inv = true,      -- Refresh inventory
                             sel = true,      -- Select slot (slot)
                             eqp = true,      -- Equip item in slot (side)
                             rds = true,      -- Redstone signal
                             name = true,     -- change name
                             note = true,     -- change description
                             color = true,    -- change color
                             gpsLoc = true,   -- GPS fix
                             refuel = true,   -- refuel
                             gtrQRY = true,   -- QRY
                             lock = true,     -- lock turtle
                             unlock = true,   -- unlock turtle
                           }
      if validActions[tostring(newCmdData.cmd)] then
        return doAction(newCmdData.cmd, newCmdData.action)
      end
    end
  end
end
 
local function getFuelLevel()
  benzina = turtle.getFuelLevel()
  if type(benzina) == "string" then
    fuelPercent = 101                         -- Unlimited fuel
    briquettes = 0
    fuelState = true
    return true
  else
    if benzina > 0 then
      local maxFuel = turtle.getFuelLimit()
      fuelPercent = (benzina / maxFuel) * 100 -- Fuel percentage
      briquettes = benzina / 80               -- Coal equivalent
      fuelState = true
    else
      fuelPercent = 0                         -- Out of fuel
      briquettes = 0
      fuelState = false
    end
    return true
  end
end
 
local function inventorySlots()
  local tmpSlot = turtle.getSelectedSlot()
  gtInventory = { }
  for i = 1, 16, 1 do
    turtle.select(i)
    selectedSlot = i
    gtInventory[i] = turtle.getItemCount(i)
  end
  turtle.select(tmpSlot)
  selectedSlot = turtle.getSelectedSlot()
  return true
end
 
local function checkDirections()
  up = turtle.detectUp()
  down = turtle.detectDown()
  forward = turtle.detect()
end
 
doAction = function(command, action)
  local actions = {
                    dig = function()
                            if not lockState then
                              local dig = false
                              if action == "Up" then
                                dig = turtle.digUp()
                                up = false
                              elseif action == "Forward" then
                                dig = turtle.dig()
                                forward = false
                              elseif action == "Down" then
                                dig = turtle.digDown()
                                down = false
                              end
                              gtInventory[selectedSlot] = turtle.getItemCount(selectedSlot)
                              if dirCheck then checkDirections() end
                              return dig
                            else
                              return false
                            end
                          end,
                    atk = function()
                            if not lockState then
                              local attack = turtle.attack()
                              if dirCheck then checkDirections() end
                              return attack
                            else
                             return false
                            end
                          end,
                    dcToggle = function()
                                 if not lockState then
                                   dirCheck = action
                                   if dirCheck then checkDirections() end
                                   return true
                                 else
                                   return false
                                 end
                               end,
                    sCmd = function()
                             if not lockState then
                               term.setBackgroundColor(black)
                               term.clear()
                               term.setCursorPos(2, 2)
                               shell.run(action)
                               if dirCheck then checkDirections() end
                               return true
                             else
                               return false
                             end
                           end,
                    put = function()
                            if not lockState then
                              local place = false
                              if action == "Up" then
                                place = turtle.placeUp()
                                up = true
                              elseif action == "Forward" then
                                place = turtle.place()
                                forward = true
                              elseif action == "Down" then
                                place = turtle.placeDown()
                                down = true
                              else
                                place = turtle.place(action)
                              end
                              gtInventory[selectedSlot] = turtle.getItemCount(selectedSlot)
                              if dirCheck then checkDirections() end
                              return place
                            else
                              return false
                            end
                          end,
                    inv = function()
                            if not lockState then
                              inventorySlots()
                              return true
                            else
                              return false
                            end
                          end,
                    sel = function()
                            if not lockState then
                              if tonumber(action) ~= nil then
                                selectedSlot = turtle.getSelectedSlot()                       -- get current slot
                                gtInventory[selectedSlot] = turtle.getItemCount(selectedSlot) -- inventory current slot
                                local select = turtle.select(action)                          -- select user chosen slot
                                selectedSlot = turtle.getSelectedSlot()
                                gtInventory[selectedSlot] = turtle.getItemCount(selectedSlot) -- inventory user chosen slot
                                return select
                              else
                                return false
                              end
                            end
                          end,
                    rds = function()
                            if not lockState then
                              if action then
                                rs.setOutput("front", true)
                                gtRedstone = true
                              else
                                rs.setOutput("front", false)
                                gtRedstone = false
                              end
                              return true
                            else
                              return false
                            end
                          end,
                    gtrQRY = function()
                               getFuelLevel()
                               gtRedstone = rs.getOutput("front")
                               if dirCheck then checkDirections() end
                               loc.x, loc.y, loc.z = gps.locate(1)
                               if not loc.x then
                                 loc.x, loc.y, loc.z = "No GPS Fix", "No GPS Fix", "No GPS Fix"
                                 return true
                               else
                                 return true
                               end
                             end,
                    move = function()
                             if not lockState then
                               if action == "forward" then
                                 local moveForward = turtle.forward()
                                 if dirCheck then checkDirections() end
                                 if moveForward then
                                   rs.setOutput("front", false)
                                   gtRedstone = false
                                   getFuelLevel()
                                   return true
                                 else
                                   return false
                                 end
                               elseif action == "back" then
                                 local moveBack = turtle.back()
                                 if dirCheck then checkDirections() end
                                 if moveBack then
                                   rs.setOutput("front", false)
                                   gtRedstone = false
                                   getFuelLevel()
                                   return true
                                 else
                                   return false
                                 end
                               elseif action == "left" then
                                 local turnLeft = turtle.turnLeft()
                                 rs.setOutput("front", false)
                                 gtRedstone = false
                                 if dirCheck then checkDirections() end
                                 return turnLeft
                               elseif action == "right" then
                                 local turnRight = turtle.turnRight()
                                 rs.setOutput("front", false)
                                 gtRedstone = false
                                 if dirCheck then checkDirections() end
                                 return turnRight
                               elseif action == "up" then
                                 local moveUp = turtle.up()
                                 if dirCheck then checkDirections() end
                                 if moveUp then
                                   rs.setOutput("front", false)
                                   gtRedstone = false
                                   getFuelLevel()
                                   return true
                                 else
                                   return false
                                 end
                               elseif action == "down" then
                                 local moveDown = turtle.down()
                                 if dirCheck then checkDirections() end
                                 if moveDown then
                                   rs.setOutput("front", false)
                                   gtRedstone = false
                                   getFuelLevel()
                                   return true
                                 else
                                   return false
                                 end
                               end
                             else
                               return false
                             end
                           end,
                    name = function()
                             if not lockState then
                               gtSettings.name = tostring(action)
                               os.setComputerLabel(gtSettings.name)
                               saveData()
                               return true
                             else
                               return false
                             end
                           end,
                    note = function()
                             if not lockState then
                               gtSettings.note = tostring(action)
                               saveData()
                               return true
                             else
                               return false
                             end
                           end,
                    color = function()
                              if not lockState then
                                gtSettings.color = tostring(action)
                                saveData()
                                return true
                              else
                                return false
                              end
                            end,
                    refuel = function()
                               if not lockState then
                                 local fuelUp = turtle.refuel(action)
                                 getFuelLevel()
                                 gtInventory[selectedSlot] = turtle.getItemCount(selectedSlot)
                                 if fuelUp then
                                   return true
                                 else
                                   return false
                                 end
                               else
                                 return false
                               end
                             end,
                    eqp = function()
                            if not lockState then
                              local equip = false
                              if action == "right" and action ~= netSide then
                                equip = turtle.equipRight()
                                --if not equip then equip = turtle.unequipRight() end
                                gtInventory[selectedSlot] = turtle.getItemCount(selectedSlot)
                              elseif action == "left" and action ~= netSide then
                                equip = turtle.equipLeft()
                                --if not equip then equip = turtle.unequipLeft() end
                                gtInventory[selectedSlot] = turtle.getItemCount(selectedSlot)
                              end
                              return equip
                            else
                              return false
                            end
                          end,
                    gpsLoc = function()
                               if not lockState then
                                 getFuelLevel()
                                 if dirCheck then checkDirections() end
                                 loc.x, loc.y, loc.z = gps.locate(2)
                                 if not loc.x then
                                   loc.x, loc.y, loc.z = "No GPS Fix", "No GPS Fix", "No GPS Fix"
                                   return false
                                 else
                                   return true
                                 end
                               else
                                 return false
                               end
                             end,
                    lock = function()
                             if not lockState then
                               if gtSettings.password == action then
                                 lockState = true
                                 return true
                               else
                                 return false
                               end
                             else
                               return false
                             end
                           end,
                    unlock = function()
                               if lockState then
                                 if gtSettings.password == action then
                                   lockState = false
                                   return true
                                 else
                                   return false
                                 end
                               else
                                 return false
                               end
                             end,
                  }
  for cmd, func in pairs(actions) do
    if tostring(cmd) == command then
      return func()
    end
  end
end
 
local function getColor(assignment)
  local colorBurst = {
                       P = "Purple",
                       B = "Blue",
                       S = "Sky",
                       G = "Green",
                       R = "Red",
                       O = "Orange",
                       N = "Brown",
                       I = "Silver",
                     }
  for k, v in pairs(colorBurst) do
    if assignment == tostring(k) then
      return v
    end
  end
end
 
local function drawElement(x, y, w, h, txColor, bgColor, text)
  local deText = tostring(text)
  if bgColor then term.setBackgroundColor(bgColor) end
  if w > #deText or h > 1 then       -- We're 'drawing' something more than text
    for i = 1, h, 1 do
      term.setCursorPos(x, y + i - 1)
      term.write(string.rep(" ", w)) -- Draw the 'element' (box/rectangle/line-seg)
    end
  end
  if deText ~= "" and deText ~= "nil" then
    if txColor then term.setTextColor(txColor) end
    if w < #deText then w = #deText end -- Ensure minimum length
    local xW = (x + math.floor(w / 2)) - math.floor(#deText / 2) -- Center the text horizontally
    local xH = y + math.floor(h / 2)    -- Center the text vertically
    term.setCursorPos(xW, xH)
    term.write(deText)
  end
end
 
local function staticTermScreen()
  local titleText = gtSettings.name .. " / # " .. os.getComputerID() .. " / " .. "gtHost " .. gtHver
  term.setBackgroundColor(black)
  term.clear()
  drawElement(1, 1, termX, 1, white, blue, titleText)
  drawElement(2, 3, 1, 1, gray, black, "Name:           ")
  drawElement(2, 4, 1, 1, nil, nil, "Description:    ")
  drawElement(2, 5, 1, 1, nil, nil, "Assigned Color: ")
  drawElement(2, 7, 1, 1, nil, nil, "Fuel:")
  drawElement(2, 8, 1, 1, nil, nil, "Coal equiv:")
  drawElement(2, 10, 1, 1, nil, nil, "Redstone output:")
  drawElement(2, 11, 1, 1, nil, nil, "Lock state:")
  drawElement(2, termY - 1, 1, 1, nil, nil, "Last Action Success:")
  drawElement(18, 3, 1, 1, white, nil, gtSettings.name)
  drawElement(18, 4, 1, 1, silver, nil, gtSettings.note)
  drawElement(18, 5, 1, 1, nil, nil, getColor(gtSettings.color))
end
 
local function drawTermScreen()
  drawElement(14, 7, 1, 1, yellow, black, fuelPercent .. "%   ")
  drawElement(19, 7, 1, 1, silver, nil, "(" .. turtle.getFuelLevel() .. " / " .. turtle.getFuelLimit() .. ")     ")
  drawElement(14, 8, 1, 1, nil, nil, briquettes .. " coal   ")
  drawElement(23, 11, 1, 1, nil, nil, tostring(lockState) .. "  ")
  drawElement(23, 10, 1, 1, red, nil, tostring(gtRedstone) .. "  ")
  drawElement(23, termY - 1, 1, 1, gtSuccess and green or red, nil, tostring(gtSuccess) .. "  ")
end
 
local function foregroundShell()
  term.setBackgroundColor(black)
  term.clear()
  term.setCursorPos(1, 1)
  if fs.exists(tArgs[1]) then
          shell.run(tArgs[1])
  end
  term.clear()
  term.setTextColor(white)
  term.setCursorPos(1, 1)
  shell.run("shell")
  rednet.close(netSide)
  term.setBackgroundColor(black)
  term.setTextColor(white)
  term.clear()
  term.setCursorPos(1, 1)
  term.write("gtHost is OFFLINE")
  term.setCursorPos(1, 3)
end
 
local function gtHostKernel()
  while true do
    if not tArgs[1] then
      drawTermScreen()
    end
    gtSuccess = netReceive()
    reportStatus()
  end
end
 
local function firstRun()
  if not fs.exists("/data") then fs.makeDir("/data") end
  gtSuccess = false
  -- Set host name
  drawElement(2, 2, 23, 1, white, nil, "Please name this turtle")
  drawElement(3, 3, 22, 1, nil, nil, "(8 characters or less)")
  while true do
    term.setCursorPos(2, 5)
    local newName = tostring(read())
    if newName ~= "" and newName ~= "nil" then
      if #newName > 8 then newName = newName:sub(1, 8) end
      gtSettings.name = newName
      -- Set turtle label
      os.setComputerLabel(gtSettings.name)
      break
    end
  end
  -- Set host description
  term.clear()
  drawElement(2, 2, 22, 1, white, black, "Please type in a short")
  drawElement(2, 3, 22, 1, nil, nil, "description")
  while true do
    term.setCursorPos(2, 5)
    local newDesc = tostring(read())
    if newDesc ~= "" and newDesc ~= "nil" then
      gtSettings.note = newDesc
      break
    end
  end
   -- Select color
  local colorBurst = {
                       P = "Purple",
                       B = "Blue",
                       S = "Sky",
                       G = "Green",
                       R = "Red",
                       O = "Orange",
                       N = "Brown",
                       I = "Silver",
                     }
  term.clear()
  drawElement(2, 2, 14, 1, white, black, "Select a color")
  local ttY = 4
  for g, h in pairs(colorBurst) do
    term.setCursorPos(2, ttY)
    term.write(tostring(g) .. " = " .. h)
    ttY = ttY + 1
  end
  term.setCursorPos(2, 13)
  while true do
    local newColor = string.upper(tostring(read()))
    if newColor ~= "" and newColor ~= "nil" then
      for v, w in pairs(colorBurst) do
        if newColor == tostring(v) then
          gtSettings.color = tostring(v)
          --return false
          break
        end
      end
    end
    if newColor ~= "" and newColor ~= "nil" then break end
  end
  -- Set password
  term.clear()
  drawElement(2, 2, 1, 1, nil, nil, "Would you like to password")
  drawElement(2, 3, 1, 1, nil, nil, "protect this turtle?")
  term.setCursorPos(2, 5)
  local lockQ = string.lower(read())
  if lockQ == "y" or lockQ == "yes" then
    drawElement(2, 7, 1, 1, nil, nil, "Please enter a password...")
    term.setCursorPos(2, 9)
    local pass = read()
    if pass == "" or pass == nil or pass == "nil" then
      gtSettings.password = false
    else
      gtSettings.password = pass
    end
  end
  saveData()
end
 
local function initMe()
  term.setBackgroundColor(black)
  term.clear()
  if not fs.exists(config) then firstRun() end
  checkDirections()
  selectedSlot = turtle.getSelectedSlot()
  drawElement(2, 2, 1, 1, white, nil, "Ingesting configuration data . . .")
  local gtHConfig = fs.open(config, "r") or error("initMe(): Cannot open " .. config .. " for reading", 0)
  local gtHCfg = gtHConfig.readAll()
  gtSettings = textutils.unserialize(gtHCfg)
  gtHConfig.close()
  if not gtSettings.newColors then
    if gtSettings.color == "L" then
      gtSettings.color = "S"
    elseif gtSettings.color == "Y" then
      gtSettings.color = "I"
    end
    gtSettings.newColors = true
    saveData()
  end
  if gtSettings.password then
    lockState = true
  end
  drawElement(2, 4, 1, 1, nil, nil, "Getting fuel level . . .")
  getFuelLevel()
  drawElement(2, 5, 1, 1, nil, nil, "Scanning inventory . . .")
  inventorySlots()
  drawElement(2, 6, 1, 1, nil, nil, "Setting redstone . . .")
  if rs.getOutput("front") then
    gtRedstone = true
  else
    gtRedstone = false
  end
  drawElement(2, 8, 1, 1, nil, nil, "Configuring hardware . . .")
  for _, side in ipairs(rs.getSides()) do
    if peripheral.isPresent(side) then
      local perp = peripheral.getType(side)
      if tostring(perp) == "modem" then
        if peripheral.call(side, "isWireless") == true then
          netSide = side
          if not rednet.isOpen(netSide) then
            rednet.open(netSide)
          end
          drawElement(2, 10, 1, 1, nil, nil, "Hosting services . . .")
          rednet.host("gtRemote", gtSettings.name)
          if os.clock() < 5 then sleep(math.random(1, 3)) end -- This is so every turtle doesn't report in at once
          drawElement(2, 11, 1, 1, nil, nil, "Acquiring GPS fix . . .")
          loc.x, loc.y, loc.z = gps.locate(2)
          if not loc.x then
            loc.x, loc.y, loc.z = "No GPS Fix", "No GPS Fix", "No GPS Fix"
          end
          break
        end
      end
    end
  end
  if netSide == "none" then
    term.setBackgroundColor(black)
    term.clear()
    drawElement(2, 2, 1, 1, red, black, "No wireless")
    drawElement(2, 3, 1, 1, nil, nil, "modem detected!")
    drawElement(2, 5, 1, 1, nil, nil, "gtHost REQUIRES")
    drawElement(2, 6, 1, 1, nil, nil, "a wireless modem.")
    term.setCursorPos(1, 9)
    quit = "YES"
    return
  end
  gtSuccess = true
  staticTermScreen()
end
 
initMe()
 
if quit == "YES" then return end
if tArgs[1] then
        parallel.waitForAny(foregroundShell, gtHostKernel)
else
  gtHostKernel()
end
