View difference between Paste ID: HMGUMEm1 and 2UJDwnUA
SHOW: | | - or go back to the newest paste.
1
--[[
2
Blu-Bank(server) / ATM(client) code
3
4
By CreeperGoBoom]]
5
6
--VARS
7
local version = "V1.0"
8
local range = 2
9
local newAccAmount = 10000  --How much to start players off with on their first use
10
local currency= { --ensure each item is in it's own table to ensure correct order of dispensing at highest level first (like an ATM giving you $100 or $50 notes for example)
11
--current exchange rates based mostly on projecte rates, tweaked for fairness
12
{["minecraft:emerald_block"] = 147456},
13
{["minecraft:diamond_block"] = 73728},
14
{["minecraft:emerald"] = 16384},
15
{["minecraft:gold_block"] = 18432},
16
{["minecraft:diamond"] = 8192},
17
{["minecraft:iron_block"] = 2304},
18
{["minecraft:gold_ingot"] = 2048},
19
{["minecraft:iron_ingot"] = 256},
20
{["minecraft:redstone"] = 64},
21
}
22
23
local function currencyLookupSimple()
24
  local output = {}
25
  for count, t in pairs(currency) do
26
    for itemName,cost in pairs(t) do
27
      output[itemName] = cost
28
    end
29
  end
30
  return output
31
end
32
33
local simpleCurrency = currencyLookupSimple()
34
--returns an unordered currency list and allows things like if simpleCurrency[name] == cost then
35
36
local blacklistNames= {
37
  "Creeper",
38
  "Skeleton",
39
  "Spider",
40
  "Enderman",
41
  "Chicken",
42
  "Cow",
43
  "Spider",
44
  "Slime",
45
  "Villager",
46
  "Bee",
47
  "Wolf",
48
  "Ocelot",
49
  "Squid"
50
  }
51
  
52
local keysraw = {
53
  {
54
    ["a"] = 30,
55
  },
56
  {
57
    ["b"] = 48,
58
  },
59
  {
60
    ["c"] = 46,
61
  },
62
  {
63
    ["d"] = 32,
64
  },
65
  {
66
    ["e"] = 18,
67
  },
68
  {
69
    ["f"] = 33,
70
  },
71
  {
72
    ["g"] = 34,
73
  },
74
  {
75
    ["h"] = 35,
76
  },
77
  {
78
    ["i"] = 23,
79
  },
80
  {
81
    ["j"] = 36,
82
  },
83
  {
84
    ["k"] = 37,
85
  },
86
  {
87
    ["l"] = 38,
88
  },
89
  {
90
    ["m"] = 50,
91
  },
92
  {
93
    ["n"] = 49,
94
  },
95
  {
96
    ["o"] = 24,
97
  },
98
  {
99
    ["p"] = 25,
100
  },
101
  {
102
    ["q"] = 16,
103
  },
104
  {
105
    ["r"] = 19,
106
  },
107
  {
108
    ["s"] = 31,
109
  },
110
  {
111
    ["t"] = 20,
112
  },
113
  {
114
    ["u"] = 22,
115
  },
116
  {
117
    ["v"] = 47,
118
  },
119
  {
120
    ["w"] = 17,
121
  },
122
  {
123
    ["x"] = 45,
124
  },
125
  {
126
    ["y"] = 21,
127
  },
128
  {
129
    ["z"] = 44,
130
  },
131
  {
132
    [ "1" ] = 2,
133
  },
134
  {
135
    [ "2" ] = 3,
136
  },
137
  {
138
    [ "3" ] = 4,
139
  },
140
  {
141
    [ "4" ] = 5,
142
  },
143
  {
144
    [ "5" ] = 6,
145
  },
146
  {
147
    [ "6" ] = 7,
148
  },
149
  {
150
    [ "7" ] = 8,
151
  },
152
  {
153
    [ "8" ] = 9,
154
  },
155
  {
156
    [ "9" ] = 10,
157
  },
158
  {
159
    [ "0" ] = 11,
160
  },
161
}
162
163
--Creates a list of all alphanumeric chars using the table above
164
local keys = {}
165
for i = 1,#keysraw do
166
  for a,_ in pairs(keysraw[i]) do
167
    keys[i]=a
168
  end
169
end
170
171
--PRELIMINARY--
172
173
local function httpGet(stringURL, stringFileNameToSaveTo)
174
  local h, err = http.get(stringURL)
175
  if not h then printError(err) return nil end
176
  local f = fs.open(stringFileNameToSaveTo, "w")
177
  f.write(h.readAll())
178
  f.close()
179
  h.close()
180
  return true
181
end
182
183
--Get API if don't already have
184
if not fs.exists("apis/CGBCoreLib.lua") then
185
  if not httpGet("https://pastebin.com/raw/xuMVS2GP", "apis/CGBCoreLib.lua") then
186
    error("Error: Dependancy 'CGBCoreLib' could not be downloaded. Please connect your internet and restart")
187
  end
188
end
189
190
local cgb = require("apis/CGBCoreLib") --Contains complete function library used accross multiple programs and to minimize code size.
191
192
cgb.saveConfig("data/keydata.lua",keys)
193
--For API check
194
local requiredAPIFuncs = {
195
  "getAnswerWithPrompts",
196
  "saveConfig",
197
  "fileWrite",
198
  "findPeripheralOnSide",
199
  "isInList",
200
  "stringToTable",
201
  }
202
203
--Check API to ensure not outdated
204
for _ , func in pairs(requiredAPIFuncs) do 
205
  if not cgb[func] then
206
    if not httpGet("https://pastebin.com/raw/xuMVS2GP", "apis/CGBCoreLib.lua") then
207
      error("Error: Your version of CGBCoreLib is outdated! Please connect your internet and restart!")
208
    else
209
      os.reboot()
210
    end
211
  end
212
end
213
214
local pcTypes = {"Bank","ATM"}
215
--Now check to see what this is (Bank or ATM)
216
local function pcTypeCheck()
217
  local output=nil
218
  for key, type in pairs(pcTypes) do
219
    if fs.exists("data/blubank/" .. type .. ".type") then
220
      output = type
221
      return true,output
222
    end
223
  end
224
  if not output then
225
    return nil
226
  end
227
end
228
229
local modem = nil
230
--New computer. creates a blank file as a type placeholder
231
--Find modem, make sure it is wireless and open rednet.
232
--using sides first
233
local sides = redstone.getSides()
234
for _,side in pairs(sides) do
235
  if peripheral.getType(side) == "modem" and peripheral.call(side,"isWireless") then
236
    modem = true --no point with a wrap since we have found a modem to open rednet directly.
237
    rednet.open(side)
238
    break
239
  end
240
end
241
if not modem then --Wireless modem not on sides, must be on network
242
  local modemList = cgb.getPeripherals("modem")
243
  for _,v in pairs(modemList) do
244
    print(v)
245
    if peripheral.call(v,"isWireless") then
246
      modem = true
247
      rednet.open(v)
248
      break
249
    end
250
  end
251
  if not modem then
252
    error("Error: Wireless modem not found")
253
  end
254
end
255
256
local ok, pcType = pcTypeCheck()
257
if not ok then --For new configurations
258
  local nonexisting
259
  local event = {}
260
  pcType = cgb.getAnswerWithPrompts("What type of computer is this?",pcTypes)
261
  cgb.fileWrite("data/blubank/" .. pcType .. ".type")  --Don't have to repeat this anywhere now
262
  if pcType == "Bank" then
263
    --Bank server selected. Ensure no other bank server active by pinging for server.
264
    --Start a 3 second timer for if there is no answer to ping.
265
    print("Reminder: This chunk must now remain loaded at all times to avoid problems with ATMs working. Press ENTER to continue.")
266
    io.read()
267
    print("Pinging for existing bank server...")
268
    nonexisting = os.startTimer(3)
269
    rednet.broadcast("Existing?","Blu-bank-SSL")
270
    repeat 
271
      event = {os.pullEvent()}
272
    --Do all checks here.
273
    until 
274
      (event[1] == "rednet_message" and event[3] == "yes") 
275
    or 
276
      (event[1] == "timer" and event[2] == nonexisting)
277
    --We have already checked for other event args in repeat until so no need to repeat them below.
278
    if event[1] == "rednet_message" then
279
      --Bank server already exists. Ensure that type remains unset.
280
      print("There is already a Bank server active. Restarting!")
281
      fs.delete("data/blubank/" .. pcType ..".type")
282
      sleep(2)
283
      os.reboot()
284
    elseif event[1] == "timer" then
285
      --No bank server exists or active
286
      print("Other bank server not found. Bank server configured!")
287
      sleep(2)
288
    end
289
  end
290
end
291
292
if pcType == "ATM" then
293
  rs.setOutput("bottom",true)
294
end
295
296
local function resetTerm()
297
  term.setBackgroundColor(colors.white)
298
  term.clear()
299
  if term.isColor() then
300
  term.setTextColor(colors.blue)
301
  elseif not term.isColor() then
302
  term.setTextColor(colors.black)
303
  end
304
  term.setCursorPos(1,1)
305
  if commands ~= nil and pcType == "Bank" then
306
    print("Blu-Bank OS " .. version .. " Bank")
307
    print("Command Bank server active!")
308
  elseif not commands then
309
    print("Blu-Bank OS " .. version .. " " .. pcType)
310
    if pcType == "Bank" then
311
      print("Bank server active!")
312
    else
313
      print("Accessing bank server...")
314
    end
315
  end
316
end
317
318
local sign
319
local chest
320
local trash
321
local sensor=nil
322
local config = {}
323
if pcType == "ATM" then --no point trying to wrap a sensor for bank server.
324
  sensor = peripheral.wrap(cgb.findPeripheralOnSide("plethora:sensor"))
325
  if not sensor then
326
    error("Error: Sensor not found. The ATM requires a sensor turtle with wireless modem to function")
327
  elseif sensor then
328
    config["sensor"]=cgb.findPeripheralOnSide("plethora:sensor")
329
  end
330
  if not fs.exists("data/blubank/config.lua") then
331
    --Chests
332
    repeat
333
      print("What is the network name of your input chest?")
334
      input = io.read()
335
      chest = peripheral.wrap(input)
336
      if not chest then
337
        print("Chest not found or input network name not a chest or storage. please check network name and try again")
338
      end
339
    until chest
340
    config["chest"]= input
341
    --trash for deposits to delete items
342
    repeat
343
      print("What is the network name of your trash chest?")
344
      input = io.read()
345
      trash = peripheral.wrap(input)
346
      if not trash then
347
        print("Chest not found or input network name not a chest or storage. please check network name and try again")
348
      end
349
    until trash
350
    config["trash"] = input
351
    --configure screens
352
    print("Please right click on the monitor you wish to use as greeting sign")
353
    print("OR invoke a redstone signal for network name / side")
354
    repeat
355
      event,monitorraw,x,y = os.pullEvent()
356
    until event == "monitor_touch" or event == "redstone"
357
    if event == "monitor_touch" then
358
      config["greeting_monitor"]=monitorraw
359
      monitor = peripheral.wrap(monitorraw)
360
    elseif event == "redstone" then
361
      repeat
362
        print("What is the network name / side of the screen?")
363
        input = io.read()
364
        monitor = peripheral.wrap(input)
365
        if not monitor then
366
          print("Entered network name / side not found. Please try again")
367
        end
368
      until monitor
369
      config["greeting_monitor"]=input
370
    end
371
    monitor.write("BLU-BANK OS")
372
    
373
    
374
    print("Please right click on the monitor you wish to use as currency sign")
375
    print("OR invoke a redstone signal for network name / side")
376
    repeat
377
      event,monitorraw,x,y = os.pullEvent()
378
    until event == "monitor_touch" or event == "redstone"
379
    if event == "monitor_touch" then
380
      config["currency_monitor"]=monitorraw
381
      cmonitor = peripheral.wrap(monitorraw)
382
    elseif event == "redstone" then
383
      repeat
384
        print("What is the network name / side of the screen?")
385
        input = io.read()
386
        cmonitor = peripheral.wrap(input)
387
        if not cmonitor then
388
          print("Entered network name / side not found. Please try again")
389
        end
390
      until cmonitor
391
    config["currency_monitor"]=input
392
    end    
393
    cmonitor.write("BLU-BANK OS")
394
    
395
    print("Please right click on the monitor you wish to use as ATM Building sign")
396
    print("OR invoke a redstone signal for network name / side")
397
    repeat
398
      event,monitorraw,x,y = os.pullEvent()
399
    until event == "monitor_touch" or event == "redstone"
400
    if event == "monitor_touch" then
401
      config["sign_monitor"]=monitorraw
402
      sign = peripheral.wrap(monitorraw)
403
    elseif event == "redstone" then
404
      repeat
405
        print("What is the network name / side of the screen?")
406
        input = io.read()
407
        sign = peripheral.wrap(input)
408
        if not sign then
409
          print("Entered network name / side not found. Please try again")
410
        end
411
      until sign
412
    config["sign_monitor"]=input
413
    end    
414
    sign.write("BLU-BANK OS")
415
    
416
    --get and save id of bank server
417
    rednet.broadcast("bank id?","Blu-bank-SSL")
418
    event, id, message, protocol = os.pullEvent("rednet_message")
419
    config.bankId = tonumber(id)
420
    cgb.saveConfig("data/blubank/config.lua",config)
421
  else
422
    --Config exists... load all devices and settings
423
    config = cgb.loadConfig("data/blubank/config.lua")
424
    
425
    --This allows a bank to be moved to a new computer without any ATM config needed.
426
    --Will stop ATMs turning on if server is not working
427
    rednet.broadcast("bank id?","Blu-bank-SSL")
428
    term.clear()
429
    term.setCursorPos(1,1)
430
    print("BLU-BANK OS")
431
    print("Querying bank server...")
432
    expired = os.startTimer(1)
433
    repeat
434
      event, id, message, protocol = os.pullEvent()
435
    until (event == "rednet_message" and message == "ok") or (event == "timer" and id == expired)
436
    if event == "rednet_message" then
437
      config.bankId = tonumber(id)
438
      monitor = peripheral.wrap(config.greeting_monitor)
439
      monitor.clear()
440
      monitor.setCursorPos(1,1)
441
      monitor.write("Blu-bank OS")
442
      cmonitor = peripheral.wrap(config.currency_monitor)
443
      sensor = peripheral.wrap(config.sensor)
444
      chest = peripheral.wrap(config.chest)
445
      trash = peripheral.wrap(config.trash)
446
      sign = peripheral.wrap(config.sign_monitor) 
447
    elseif id == expired then
448
      print("Bank server not responding! auto restarting in:")
449
      for i = 5,1,-1 do
450
        print(i .. "...")
451
        sleep(1)
452
      end
453
      os.reboot()
454
    end
455
  end
456
end 
457
458
local function updateCurrencyScreen()
459
  cmonitor.setBackgroundColor(colors.white)
460
  cmonitor.clear()
461
  cmonitor.setTextScale(1)
462
  cmonitor.setCursorPos(1,1)
463
  if cmonitor.isColor then
464
    cmonitor.setTextColor(colors.blue)
465
  else
466
    cmonitor.setTextColor(colors.black)
467
  end
468
  local ctxt
469
  cmonitor.write("Credit rates:")
470
  cmonitor.setCursorPos(1,2)
471
  for count, t in pairs(currency) do
472
    local line = count + 2
473
    for itemname,cost in pairs(t) do
474
      _, simpleName, simpleName2 = cgb.stringToVars(itemname)
475
      if simpleName2 then
476
        cmonitor.write(simpleName .. " " .. simpleName2 .. ": " ..cost)
477
      elseif not simpleName2 then
478
        cmonitor.write(simpleName .. ": " ..cost)
479
      end
480
    end
481
    cmonitor.setCursorPos(1,line)
482
  end
483
end
484
485
local function updateMonitor(stringNewMsg,colorName)
486
  monitor.setBackgroundColor(colors.white)
487
  if colorName then 
488
    monitor.setTextColor(colorName)
489
  else
490
    monitor.setTextColor(colors.blue)
491
  end
492
  if not monitor.isColor() then
493
    monitor.setTextColor(colors.black)
494
  end
495
  monitor.setTextScale(2)
496
  monitor.clear()
497
  monitor.setCursorPos(13,1)
498
  monitor.write("Blu-Bank OS")
499
  monitor.setCursorPos(8,2)
500
  monitor.write(stringNewMsg)
501
end
502
503
local function buildingSign()
504
  sign.setBackgroundColor(colors.white)
505
  sign.clear()
506
  sign.setCursorPos(2,1)
507
  sign.setTextScale(5)
508
  sign.setTextColor(colors.blue)
509
  sign.write("BLU-BANK")
510
end
511
512
513
if pcType == "Bank" and not commands then
514
  print("Warning: This pc is not a command pc, as such only deposits and store purchases are available. Please ensure everyone knows that direct withdrawals are not possible.")
515
end
516
517
--Prevents a hacker from making any transactions on other players behalf. must be called.
518
local function authenticate(stringAuthType)
519
  rednet.send(senderID, "authorization required")
520
  event, senderID, message = os.pullEvent()
521
  if message == "password?" then
522
    local pass = ""
523
    for i = 1, 20 do
524
      k = math.random(1,#keys)
525
      pass = pass .. keys[k]
526
    end
527
    passExpired = os.startTimer(1) --if ATM received password it should have bounced back within 1 second.
528
    rednet.send(senderID,"pass: " .. pass)
529
    repeat
530
      event, senderID, message = os.pullEvent()
531
    until (event == "rednet_message" and message == pass) or (event == "timer" and senderID == passExpired)
532
    if event == "rednet_message" then 
533
      rednet.send(senderID, stringAuthType .. " Authorized")
534
    elseif event == "timer" then
535
      rednet.send(senderID, "Authorization timed out!")
536
    end
537
  end
538
end
539
540
local sensordata={}
541
local function updateSensorData()
542
  sensordata=sensor.sense() --this is also stored in upper sensordata so we can still do whatever we want with it
543
end
544
545
local function getPlayerInRange()
546
  local id = nil
547
  updateSensorData()
548
  for i,_ in pairs(sensordata) do
549
    if sensordata[i].x > -range and 
550
    sensordata[i].x < range and 
551
    sensordata[i].z > -range and 
552
    sensordata[i].z < range and
553
    sensordata[i].y > -range and
554
    sensordata[i].y < range then
555
      if not cgb.isInList(sensordata[i].name,blacklistNames) then
556
        id = sensordata[i].name
557
        return true, id--ensures only one player is found at a time. also allows id to be discarded if not needed at the time.
558
      end
559
    end
560
  end
561
end
562
563
564
local cash = {}
565
local event
566
local function secondary()
567
  local messagedata = {}
568
  local commanddata = {}
569
  local funds = {}
570
  local bal = 0
571
  while true do
572
    event, senderID, message, protocol = os.pullEvent("rednet_message")
573
    if protocol == "Blu-bank-SSL" then --hard protocol name for players to guess and take over the server with... especially since they dont know how the commands are even sent or read. (Whatever you do, DO NOT TELL THEM!)
574
      if pcType == "Bank" then
575
        if message == "Existing?" then
576
          rednet.send(senderID,"yes") --makes sure reply is securely sent to enquiring computer.
577
        elseif message == "bank id?" then
578
          rednet.send(senderID,"ok")
579
        end
580
      end
581
    end
582
    --
583
    if pcType == "Bank" then
584
      --print(message)
585
      if commands ~= nil then --allows give command to be sent using ATMs
586
      --limit commands to give only
587
        if message:find("command") and message:find("give") then 
588
          print(message)
589
          messagedata = cgb.stringToTable(message)
590
          for i = 3,#messagedata do
591
            commanddata[i-2]=messagedata[i]
592
          end
593
          commands[messagedata[2]](table.unpack(commanddata))
594
          commanddata = {} --This is a must otherwise additional arguments are passed to the next command if your last was long.
595
        elseif message:find("command") and not message:find("give") then
596
        --Command use exceeds limit, alert everyone to a potential hacker.
597
          print("Unauthorized command attempt from PC ID: " .. senderID ..". Attempt: '" .. message .."'.")
598
          commands.say("Unauthorized access attempt...CC HACKER ALERT!")
599
        end
600
      end
601
      --"purchase playername item cost quantity"
602
      if message:find("purchase") then
603
        -- authenticate("Purchase")
604
        -- event, senderID, message, protocol = os.pullEvent("rednet_message")
605
        -- if message == "Purchase Authorized" then
606
          print(message)
607
          _, player, item, credcost, qty = cgb.stringToVarsAll(message)
608
          -- for i in string.gmatch(message, "%S+") do
609
          -- print(i)
610
          -- end
611
          --for some reason item is coming back as nil
612
          print(player .. " requested to purchase " .. qty .. " " .. item)
613
          local cost = tonumber(credcost) * qty
614
          funds = cgb.loadConfig("data/blubank/users/" .. player .. ".lua")
615
          if cost <= funds.balance then
616
            rednet.send(senderID, "purchase-success")
617
            funds.balance = funds.balance - cost
618
            cgb.saveConfig("data/blubank/users/" .. player .. ".lua",funds)
619
            commands.give(player.." " .. item .. " " .. qty)
620
          elseif cost > funds.balance then
621
            rednet.send(senderID,"insufficient funds This item costs " .. cost .. " credits and you have " .. funds.balance .. " credits!")
622
          end
623
        -- end
624
      --"withdraw playername amount"
625
      elseif message:find("withdraw") then
626
        local qty
627
        print(message)
628
        --authenticate("Withdrawal")
629
        --event, senderID, message, protocol = os.pullEvent("rednet_message")
630
        --if message == "Withdrawal Authorized" then
631
          _, player, amount = cgb.stringToVars(message)
632
          funds = cgb.loadConfig("data/blubank/users/" .. player .. ".lua")
633
          print("funds: " .. funds.balance)
634
          withdrawalRequest = tonumber(amount)
635
          if withdrawalRequest <= funds.balance then
636
            rednet.send(senderID,"withdrawal-success")
637
            commands.say(player .. " requested a withdrawal")
638
            if funds.balance == withdrawalRequest then
639
              funds.balance = 0 
640
            elseif funds.balance > withdrawalRequest then
641
              funds.balance = funds.balance - withdrawalRequest
642
            end
643
            print("Remaining: " .. funds.balance)
644
            cgb.saveConfig("data/blubank/users/" .. player .. ".lua",funds)
645
            --calculate how many of each item to give
646
            for i,tablevar in pairs(currency) do
647
              for itemName,cost in pairs(tablevar) do
648
                cash[itemName]={}
649
                qty,fraction=math.modf(withdrawalRequest / cost) --how many items can be given at this cost?
650
                --item has been calculated. give item
651
                --This avoids give not happening due to qty higher than 64 bug
652
                if qty > 64 then 
653
                  repeat
654
                    commands.give(player .. " " .. itemName .. " " .. 64)
655
                    qty = qty - 64
656
                  until qty <= 64
657
                  commands.give(player .. " " .. itemName .. " " .. qty) 
658
                elseif qty <= 64 then
659
                  commands.give(player .. " " .. itemName .. " " .. qty)
660
                end
661
                withdrawalRequest = fraction * cost --How many credits remain after item count?
662
              end
663
            end
664
            --make sure remaining unwithdrawable credits get refunded
665
            funds.balance = funds.balance + withdrawalRequest
666
            cgb.saveConfig("data/blubank/users/" .. player .. ".lua",funds)
667
          elseif withdrawalRequest > funds.balance then
668
            rednet.send(senderID, "insufficient funds Balance " .. funds.balance .. " credits.")
669
          end
670
        --end
671
      --"deposit playername amount"
672
      elseif message:find("deposit") then
673
        --authenticate("Deposit")
674
        -- event, senderID, message, protocol = os.pullEvent("rednet_message")
675
        -- if message == "Deposit Authorized" then
676
          _,player,amount = cgb.stringToVars(message)
677
          print("Depositing " .. amount .. " credits into " .. player .. "s' account") 
678
          funds = cgb.loadConfig("data/blubank/users/" .. player .. ".lua")
679
          funds.balance = funds.balance + tonumber(amount)
680
          cgb.saveConfig("data/blubank/users/" .. player .. ".lua",funds)
681
          rednet.send(senderID,"deposit-success")
682
          --Funds addition code here
683
        -- end
684
      elseif message == "password?" then
685
        --password generator code
686
        --generates a one time password which must be bounced back to server for authentication.
687
        authenticate()
688
      --"balance playername"
689
      elseif message:find("balance") then
690
        --authenticate("Balance query")
691
        -- event, senderID, message, protocol = os.pullEvent("rednet_message")
692
        -- if message == "Balance query Authorized" then
693
           _, player= cgb.stringToVars(message)
694
          if not fs.exists("data/blubank/users/" .. player .. ".lua") then
695
            print("Creating new account for: " .. player)
696
            if newAccAmount > 0 then
697
              print("Adding " .. newAccAmount .. " credits for " .. player)
698
            end
699
            funds.balance = newAccAmount
700
            cgb.saveConfig("data/blubank/users/" .. player .. ".lua",funds)
701
          else
702
            print("Loading funds of: " .. player)
703
            funds = cgb.loadConfig("data/blubank/users/" .. player .. ".lua")
704
          end
705
          rednet.send(senderID, "bal " .. funds.balance)
706
        --end
707
      elseif message:find("transfer") then
708
        _, fromplayer, toplayer, amount = cgb.stringToVarsAll(message)
709
        amount = tonumber(amount)
710
        funds = cgb.loadConfig("data/blubank/users/" .. fromplayer .. ".lua")
711
        if amount > funds.balance then
712
          rednet.send(senderID, "insufficient funds You requested to transfer " .. amount .. " credits but have " .. funds.balance .. " credits!")
713
        elseif amount <= funds.balance then
714
          rednet.send(senderID, "transfer-success")
715
          funds.balance = funds.balance - amount
716
          cgb.saveConfig("data/blubank/users/" .. fromplayer .. ".lua",funds)
717
          funds = cgb.loadConfig("data/blubank/users/" .. toplayer .. ".lua")
718
          funds.balance = funds.balance + amount
719
          cgb.saveConfig("data/blubank/users/" .. toplayer .. ".lua",funds)
720
          if commands then commands.tell(toplayer .. " " .. fromplayer .. " has just transferred you " .. amount .. " credits!") end
721
        end
722
      end
723
    elseif pcType == "ATM" then
724
      if message == "withdraw-success" then
725
        print("Success. Dispensing cash... please check your inventory :D")
726
      elseif message == "authorization required" then
727
        rednet.send(senderID, "password?")
728
        event,senderID,message = os.pullEvent("rednet_message")
729
        if message:find("pass:") then
730
          _, pass = cgb.stringToVars(message)
731
          rednet.send(senderID,pass)
732
          event,senderID,message = os.pullEvent("rednet_message")
733
          if message == "Authorization timed out!" then
734
            error("BluBank OS: err_auth_failed. Please contact server admin.")
735
          end
736
        end
737
      end
738
    end
739
  end
740
end
741
742
743
local player = "nil"
744
local playercheck
745
local playermem
746
local function main()
747
  while true do
748
    if pcType == "ATM" then
749
      buildingSign()
750
      updateMonitor(" ")
751
      resetTerm()
752
      
753
      repeat
754
        ok,player = getPlayerInRange()
755
        if not ok then
756
          sleep(1)
757
        end
758
      until ok
759
      rs.setOutput("bottom",false)
760
      playermem = player
761
      updateMonitor("WELCOME " .. player .. "!")
762
      updateCurrencyScreen()
763
      print("Welcome " .. player .. "!")
764
      rednet.send(config.bankId, "balance " .. player)
765
      --"bal balance"
766
      repeat
767
        event,senderID,message = os.pullEvent("rednet_message")
768
      until message:find("bal")
769
      _, bal= cgb.stringToVars(message)
770
      print("Your balance: " ..bal .. " credits.")
771
      print("Press W for Withdrawal")
772
      print("Press D for Deposit")
773
      print("Press T to Transfer credits")
774
      print("Press E for the Credit Exchange Store")
775
      print("Press L to Logoff")
776
      repeat
777
        event,c = os.pullEvent("char")
778
      until c
779
      if c == "l" then  --Logoff
780
        rs.setOutput("bottom",true)
781
        print("Logged off! Thanks for using Blu-Bank! See you soon!")
782
        print("Please step away from the ATM.")
783
        updateMonitor("Farewell Tenant!")
784
        cmonitor.setBackgroundColor(colors.black)
785
        cmonitor.clear()
786
        
787
        repeat
788
          ok,player = getPlayerInRange()
789
          if ok then
790
            sleep(1)
791
          end
792
        until not ok
793
      elseif c == "w" then --Withdraw
794
        print("How much would you like to withdraw?")
795
        local amount = io.read()
796
        rednet.send(config.bankId,"withdraw " .. player .. " " .. amount)
797
        event,senderID,message = os.pullEvent("rednet_message")
798
        if message == "withdrawal-success" then
799
          print("Success. Dispensing cash... please check your inventory :D")
800
          sleep(3)
801
        elseif message:find("insufficient") then
802
          local replyString = "" 
803
          local insufficientFundsMessage = {}
804
          --"insufficent funds message"
805
          messagedata = cgb.stringToTable(message)
806
          for i = 3, #messagedata do
807
            insufficientFundsMessage[i-2]=messagedata[i]
808
          end
809
          for _, str in pairs(insufficientFundsMessage) do
810
            replyString = replyString .. " " .. str
811
          end
812
          replyString = replyString .. "!"
813
          print("Insufficient funds! " .. replyString)
814
          sleep(3)
815
        end
816
      elseif c == "d" then --Deposit
817
        local itemvalue
818
        local total=0
819
        print("Take a look at the credit rates and place your deposit in the chest.")
820
        print("Press any key when you are ready to continue.")
821
        os.pullEvent("key")
822
        print("Processing, please wait.")
823
        for slot,item in pairs(chest.list()) do
824
          --if item not listed in currency, do not move
825
          if simpleCurrency[item.name] then
826
            chest.pushItems(config.trash,slot,item.count)
827
            total = total + (item.count * simpleCurrency[item.name])
828
          end
829
        end
830
        if total == 0 then
831
          print("Nothing inserted or items do not match list. please check your deposit items and try again.")
832
          sleep(3)
833
        else
834
          print("You have inserted " .. total .. " credits")
835
          print("Are you happy to finalize your deposit? Y or N")
836
          repeat  
837
            event,c = os.pullEvent("char")
838
          until c == "y" or c == "n"
839
          if c == "n" then
840
            print("Returning your deposit")
841
            for slot,item in pairs(trash.list()) do
842
              trash.pushItems(config.chest,slot,item.count)
843
            end
844
            sleep(2)
845
          elseif c == "y" then
846
            print("Sending deposit request...")
847
            rednet.send(config.bankId, "deposit " .. player .. " " .. total)
848
            event,senderID,message = os.pullEvent("rednet_message")
849
            if message == "deposit-success" then
850
              for slot,_ in pairs(trash.list()) do
851
                trash.drop(slot)
852
              end
853
              print("Deposit of " .. total .. " credits success!")
854
              sleep(3)
855
            end
856
            --deposit code
857
          end
858
        end
859
        -- elseif message == "deposit-success" then
860
          -- print("Deposit Successful!")
861
          -- sleep(3)
862
      elseif c == "t" then --Transfer
863
        print("Transfers are performed as following:")
864
        print("toPlayerName amount")
865
        print("Please ensure you have spelled the playername correctly E.g: 'playername' is not 'PlayerName'")
866
        repeat
867
          input = io.read()
868
          toplayer, amount = cgb.stringToVarsAll(input)
869
          print("You have requested: " .. amount .. " credits to be transferred to: '" .. toplayer .."'.")
870
          print("Is this correct? Press Y or N. N will cancel the operation")
871
          event,c = os.pullEvent("char")
872
        until c=="y" or c=="n"
873
        if c=="y" then
874
          rednet.send(config.bankId, "transfer " .. player .. " " .. toplayer .. " " .. amount)
875
          event,senderID,message = os.pullEvent("rednet_message")
876
          if message == "transfer-success" then
877
            print("Transfer successful!")
878
          elseif message:find("insufficient") then
879
            local replyString = "" 
880
            local insufficientFundsMessage = {}
881
            --"insufficent funds message"
882
            messagedata = cgb.stringToTable(message)
883
            for i = 3, #messagedata do
884
              insufficientFundsMessage[i-2]=messagedata[i]
885
            end
886
            for _, str in pairs(insufficientFundsMessage) do
887
              replyString = replyString .. " " .. str
888
            end
889
            replyString = replyString .. "!"
890
            print("Insufficient funds! " .. replyString)
891
            sleep(5)
892
          end
893
          sleep(3)
894
        end
895
      elseif c == "e" then --Credit Exchange Store
896
        term.clear()
897
        term.setCursorPos(1,1)
898
        print("Credit Exchange Store")
899
        print("Your Balance: " .. bal .. " credits.")  
900
        for count, t in pairs(currency) do
901
          for itemName,cost in pairs(t) do
902
            -- _, simpleName, simpleName2 = cgb.stringToVars(itemname)
903
            -- if simpleName2 then
904
              -- print(simpleName .. " " .. simpleName2 .. ": " ..cost)
905
            -- elseif not simpleName2 then
906
              -- print(simpleName .. ": " ..cost)
907
            -- end
908
            print("'" .. itemName .. "' = " .. cost)
909
          end
910
        end
911
        repeat
912
          print("Please enter as: item qty")
913
          input = io.read()
914
          item, qty = cgb.stringToVarsAll(input)
915
          if not simpleCurrency[item] then
916
            print("Please ensure you include the full name including minecraft: and your spelling is correct.")
917
          end
918
        until simpleCurrency[item]
919
        rednet.send(config.bankId, "purchase " .. player .. " " .. item .. " " .. simpleCurrency[item] .. " " ..qty)
920
        event,senderID,message = os.pullEvent("rednet_message")
921
        if message == "purchase-success" then
922
          print("Purchase successful, please check your inventory.")
923
          sleep(3)
924
        elseif message:find("insufficient") then
925
          local replyString = "" 
926
          local insufficientFundsMessage = {}
927
          --"insufficent funds message"
928
          messagedata = cgb.stringToTable(message)
929
          for i = 3, #messagedata do
930
            insufficientFundsMessage[i-2]=messagedata[i]
931
          end
932
          for _, str in pairs(insufficientFundsMessage) do
933
            replyString = replyString .. " " .. str
934
          end
935
          replyString = replyString .. "!"
936
          print("Insufficient funds! " .. replyString)
937
          sleep(5)
938
        end
939
      end
940
      --term.clear()
941
      --term.setCursorPos(1,1)
942
    elseif pcType == "Bank" then
943
      resetTerm()
944
      while true do
945
        os.pullEvent()
946
      end
947
    end
948
    --while not logged in by anyone, monitor reads 'Blu-bank ATM'. white background, blue writing if colors supported
949
    --when someone approaches, they are logged in and the screen changes to 'WELCOME playername'
950
    --When someone is logged in a redstone signal is output at bottom for door
951
    --When player leaves the detection range, a message is displayed 'Thankyou for using Blu-Bank. See you soon!' before going back to not logged in screen
952
  end
953
end
954
955
while true do
956
  parallel.waitForAny(main, secondary)
957
  --secondary()
958
end