-- FF_STORY_COMPUTER_GUARD
local function ff_story_computer_allowed()
  local label = os.getComputerLabel and os.getComputerLabel() or nil
  return fs.exists(".ff_story_computer")
    or fs.exists(".ff_titan_computer")
    or fs.exists(".ff_titan_program_id")
    or fs.exists(".ff_titan_allow_autoinstall")
    or fs.exists(".ff_titan_allow_autorun")
    or (label ~= nil and string.sub(string.lower(label), 1, 9) == "ff_titan:")
end

if not ff_story_computer_allowed() then
  return
end
-- TITAN SURFACE ELEVATOR PUZZLE
-- ComputerCraft / CC:Tweaked
-- Save as: startup
--
-- Import:
-- pastebin get PASTE_CODE startup
-- reboot
--
-- Correct answers:
-- gearbox
-- green
-- awake
-- below

local OUTPUT_SIDE = "back"
local STATE_FILE = ".titan_surface_elevator_unlocked"

local entries = {
  {
    title = "STATUS",
    body = {
      "DESCENT DRIVE",
      "",
      "Motor spins.",
      "Pulley waits.",
      "",
      "The space between them is empty.",
      "",
      "Albedo has marked this as",
      "intentional.",
      "",
      "She is rarely this polite",
      "without hiding a lock."
    }
  },
  {
    title = "COUPLER",
    body = {
      "COUPLER TAG",
      "",
      "A paper tag hangs from",
      "the empty drive socket.",
      "",
      "Written by hand:",
      "",
      "\"Do not order another one.\"",
      "\"The missing part is in Cage 7.\"",
      "",
      "Someone added below it:",
      "",
      "\"gearbox, idiot\""
    }
  },
  {
    title = "ROUTE",
    body = {
      "ROUTE LOCK",
      "",
      "Surface panel only accepts",
      "one route.",
      "",
      "Red was removed.",
      "Black was never here.",
      "",
      "The remaining button has",
      "green paint under warning tape."
    }
  },
  {
    title = "RELAY",
    body = {
      "OLD RELAY SCREEN",
      "",
      "CROWNWATCH: DEAD",
      "NEMESIS: OUT OF RANGE",
      "ALBEDO: AWAKE",
      "",
      "The screen refreshes the",
      "last line every few seconds.",
      "",
      "Nobody touched the keyboard."
    }
  },
  {
    title = "AUDIO",
    body = {
      "GATEHOUSE AUDIO",
      "",
      "Guard:",
      "Where is the knocking coming from?",
      "",
      "Albedo:",
      "Do not open the gate.",
      "",
      "Guard:",
      "The outside gate?",
      "",
      "Albedo:",
      "Below."
    }
  },
  {
    title = "UNLOCK",
    body = {
      "SURFACE AUTHORIZATION",
      "",
      "Four words required.",
      "",
      "PART",
      "ROUTE",
      "STATUS",
      "OVERRIDE",
      "",
      "The terminal does not care",
      "why you know them."
    }
  }
}

local function useColor(c)
  if term.isColor and term.isColor() then
    term.setTextColor(c)
  end
end

local function clear()
  term.setBackgroundColor(colors.black)
  term.clear()
  term.setCursorPos(1, 1)
end

local function header(title)
  clear()
  useColor(colors.lightBlue)
  print("[ TITAN DESCENT CONTROL ]")
  useColor(colors.gray)
  print("SURFACE ELEVATOR NODE")
  print("---------------------------------------")

  if title then
    useColor(colors.white)
    print(title)
    useColor(colors.gray)
    print("---------------------------------------")
  end

  useColor(colors.white)
end

local function draw(line)
  if line:find("ALBEDO") or line:find("Albedo") then
    useColor(colors.cyan)
  elseif line:find("gearbox") or line:find("green") or line:find("AWAKE") or line:find("Below") then
    useColor(colors.lime)
  elseif line:find("NEMESIS") or line:find("CROWNWATCH") or line:find("Red") or line:find("Black") then
    useColor(colors.red)
  else
    useColor(colors.white)
  end

  print(line)
end

local function waitKey()
  useColor(colors.gray)
  print("")
  print("[key] back")
  os.pullEvent("key")
end

local function show(entry)
  header(entry.title)

  for _, line in ipairs(entry.body) do
    draw(line)
  end

  waitKey()
end

local function isUnlocked()
  return fs.exists(STATE_FILE)
end

local function saveUnlocked()
  local f = fs.open(STATE_FILE, "w")
  f.write("unlocked")
  f.close()
end

local function setSignal(on)
  redstone.setOutput(OUTPUT_SIDE, on)
end

local function readWord(label)
  useColor(colors.gray)
  print("")
  useColor(colors.white)
  write(label .. ": ")
  return string.lower(read() or "")
end

local function fail()
  useColor(colors.red)
  print("")
  print("Rejected.")
  sleep(1.1)
end

local function runUnlock()
  header("SURFACE AUTHORIZATION")

  if isUnlocked() then
    useColor(colors.lime)
    print("Already authorized.")
    print("")
    print("Output side: " .. OUTPUT_SIDE)
    waitKey()
    return
  end

  useColor(colors.white)
  print("Enter authorization words.")
  print("")
  useColor(colors.gray)
  print("One word each.")
  print("No spaces.")
  print("")

  local part = readWord("PART")
  if part ~= "gearbox" then
    fail()
    return
  end

  local route = readWord("ROUTE")
  if route ~= "green" then
    fail()
    return
  end

  local status = readWord("STATUS")
  if status ~= "awake" then
    fail()
    return
  end

  local override = readWord("OVERRIDE")
  if override ~= "below" then
    fail()
    return
  end

  saveUnlocked()
  setSignal(true)

  header("AUTHORIZED")
  useColor(colors.lime)
  print("Drive signal active.")
  print("")
  useColor(colors.white)
  print("Gearbox coupling may proceed.")
  print("")
  useColor(colors.cyan)
  print("Albedo:")
  useColor(colors.white)
  print("Go on, then.")
  print("")
  print("The elevator is pretending")
  print("it wanted this.")
  waitKey()
end

if isUnlocked() then
  setSignal(true)
else
  setSignal(false)
end

while true do
  header()

  if isUnlocked() then
    useColor(colors.lime)
    print("DRIVE: AUTHORIZED")
  else
    useColor(colors.orange)
    print("DRIVE: DISCONNECTED")
  end

  useColor(colors.white)
  print("")
  print("1. Status")
  print("2. Coupler")
  print("3. Route")
  print("4. Relay")
  print("5. Audio")
  print("6. Unlock")
  print("7. Debug")
  print("")
  useColor(colors.gray)
  print("Q. close")
  useColor(colors.white)
  write("> ")

  local input = string.lower(read() or "")

  if input == "q" or input == "quit" or input == "exit" then
    clear()
    useColor(colors.gray)
    print("SESSION CLOSED")
    return
  elseif input == "1" then
    show(entries[1])
  elseif input == "2" then
    show(entries[2])
  elseif input == "3" then
    show(entries[3])
  elseif input == "4" then
    show(entries[4])
  elseif input == "5" then
    show(entries[5])
  elseif input == "6" then
    runUnlock()
  elseif input == "7" then
    header("DEBUG")
    useColor(colors.gray)
    print("RESET clears saved unlock.")
    print("ON forces signal.")
    print("OFF drops signal.")
    print("")
    useColor(colors.white)
    write("> ")
    local d = string.lower(read() or "")

    if d == "reset" then
      if fs.exists(STATE_FILE) then
        fs.delete(STATE_FILE)
      end
      setSignal(false)
      useColor(colors.orange)
      print("Reset.")
      sleep(1)
    elseif d == "on" then
      setSignal(true)
      useColor(colors.lime)
      print("Signal on.")
      sleep(1)
    elseif d == "off" then
      setSignal(false)
      useColor(colors.orange)
      print("Signal off.")
      sleep(1)
    end
  else
    useColor(colors.red)
    print("Invalid.")
    sleep(0.7)
  end
end