--I sent a copy of this to PiCkDaT earlier, but he said his PC was out of commission
--and that I should send it to you instead.  Good thing, too because I found a bug in
--shortly after.  (Sort of.  It's more an unexpected peculiarity of your web server,
--but I guess a bug's a bug.)  Anyway, I fixed it up and it works great now.  

--I'm sort of curious as to why you have so many files involved in the update process.
--it could easily be possible to have only 2 files, being a file advising of the currently
--available version and its URL and then the download itself.  Additionally, I wanted
--to ask you if some rar support could be added.  I can get you the source of unrar.dll
--if you want it.  I'll ask in the feature request forum also.

--At any rate, thanks for LPHM.  You rock.  You can use this script and any or all
--parts of it however you like.  Sell it, buy it, powder and snort it, claim you wrote
--it or that you recieved it form aliens...  Whatever's clever.  Enjoy.

--Start definitions
function pnice(x, y, text, color)
  for xo =-1,1 do
    for yo =-1,1 do
      textimg:print(x+xo, y+yo, text, black)
    end
  end
  textimg:print(x, y, text, color)
end

function drawtext()
  textimg:clear()
  for ind,line in ipairs(textlines) do
    ty = 1+(10*(ind-1))
    col = white
    if string.byte(line) == 38 then
      if string.sub(line,2,2) == "r" then
        col = red
      elseif string.sub(line,2,2) == "g" then
        col = green
      elseif string.sub(line,2,2) == "b" then
        col = black
      end
      line = string.sub(line, 3)
    end
    pnice(1, ty, line, col)
  end
end

function textline(text)
  table.insert(textlines, text)
  while table.getn(textlines) > 18 do
    table.remove(textlines, 1)
  end
  drawtext()
end

function changeline(text)
  textlines[table.getn(textlines)] = text
  drawtext()
end

function refresh()
  screen:clear()
  screen:blit(0, 0, bg)
  screen:blit(0,0,fadeimg)
  screen:blit(93,2,titleimg)
  screen:blit(96,26,shoutimg)
  screen:blit(43, 49, textimg)
  screen:blit(35, 251, pbar)
  screen.flip()
  screen.waitVblankStart()
end

function clearlines()
  textlines = {" "}
end

function sendheader(sock, filepath)
  sock:send("GET " .. filepath .. " HTTP/1.1\r\n")
  sock:send("Host: www.homemister.axspace.com\r\n")
  sock:send("User-Agent: LuaPlayer HM/" .. System.playerVer() .. " (PSP " .. System.getModel(1) .. "; CFW " .. System.cfwVersion() .. ") Update script (Khatharr did it!  Blame him!)\r\n")
  sock:send("Accept: */*;q=0.01\r\n")
  sock:send("Keep-Alive: 300\r\n")
  sock:send("Connection: keep-alive\r\n")
  sock:send("\r\n")  
end

function sweetintro()
  wsh = {}
  for i = 1,7 do
    wsh[i] = Image.createEmpty(10,10)
    wsh[i]:blit(0,0,bg,(i-1)*10,273,10,10)
  end
  temptitle = Image.createEmpty(90,10)
  tempshout = Image.createEmpty(288,10)
  temptitle:print(1,1,"LuaPlayerHM",red)
  tempshout:print(1,1,"Created by homemister and PiCkDaT",red)
  refresh()
  System.sleep(500)
  count = 0
  for i = 1,49 do
    count = (count % 7) + 1
    titleimg:clear()
    titleimg:blit(0,0,temptitle,0,0,i*2,10)
    titleimg:blit((i*2)-9, 0, wsh[count])
    refresh()
  end
  titleimg:clear()
  titleimg:blit(0,0,temptitle)
  temptitle = nil
  refresh()
  System.sleep(1000)
  count = 0
  for i = 1,68 do
    count = (count % 7) + 1
    shoutimg:clear()
    shoutimg:blit(0,0,tempshout,0,0,i*4,10)
    shoutimg:blit((i*4)-9, 0, wsh[count])
    refresh()
  end
  shoutimg:clear()
  shoutimg:blit(0,0,tempshout)
  wsh = nil
  count = nil
  tempshout = nil
  refresh()
  System.sleep(1000)
  for na = 1,32 do
    fadeimg:clear(Color.new(0,0,0,224-(na*7)))
    System.memclean()
    refresh()
  end
  fadeimg:clear()
end
--End definitions

--Start declarations
gotscript = false
bg = Image.load("./system/bg.png")
titleimg = Image.createEmpty(90,10)
shoutimg = Image.createEmpty(288,10)
fadeimg = Image.createEmpty(480,272)
fadeimg:clear(Color.new(0,0,0,224))
white = Color.new(255,255,255)
red = Color.new(255,0,0)
green = Color.new(0,255,0)
black = Color.new(0,0,0)
dkgrey = Color.new(64,64,64)
textimg = Image.createEmpty(385,180)
textlines = {" "}
hr = "------------------------------------------------"
pbar = Image.createEmpty(200,18)
--End declarations

--Start main body
sweetintro()
System.sleep(1000)
changeline("Initializing WLAN...")
refresh()
System.sleep(1000)
while not ipAddress do
  System.sleep(100)
  refresh()
  Wlan.init()
  wifi, ipAddress = pcall(function() return Wlan.getIP() end)
  if wifi == false then
    ipAddress = false
    System.message("WLAN must be initialized in order to continue.\n\nPress Yes to retry or No to exit.",1)
		butpress = System.buttonPressed(1)
		if butpress == "no" then
			System.Quit()
		end
  end
end
textline("WLAN ready.")
textline("Local IP Address is " .. ipAddress .. ".")
refresh()
server = Socket.createServerSocket(80)
textline("Server socket created on port 80.")
textline(hr)
refresh()
textline("&gConnecting to 'www.homemister.axspace.com'...")
refresh()
socket,error = Socket.connect("www.homemister.axspace.com", 80)
while not socket:isConnected() do
  refresh()
  System.sleep(100)
end
textline("Connected!  Checking version...")
refresh()
sendheader(socket, "/verdat.info")
header = ""
--Usually this second request would go down after the user's confirmation to download but your webserver
--has a 5ms timeout!  The normal timeout is 300.  Curayzee...
sendheader(socket, "/updateplayer.lua")
--This method of fetching the header is really slow, which sucks.  The waitVblank is needed because the PSP
--will freeze up if the read requests are too frequent (whipping socket reading on and off too quickly could damage)
--the hardware.  Probably the freeze is the result of a built-in hardware safeguard.  However, I may use a different
--method in the future that just grabs 50b chunks and then everything after the double-break would be used to prime
--the data variable instead of starting with it blank.  In most cases this wouldn't work, but since HM is able to
--overshoot data length on the sockets safely it could be okay.  I'm concerned about bugs, though, in cases such as this
--if I used that method then the last 50b would be too much since the file size is less than 50b, so the data of the d/l
--would contain a portion of the header for the next d/l.  :(  I'll think about it some more and try to find a better way.
while not string.find(header, "\r\n\r") do
  header = header .. socket:recv(2)
  screen.waitVblankStart()
end
if not string.find(header, "\r\n\r\n") then
  header = header .. socket:recv(1)
  screen.waitVblankStart()
end
a,b,len = string.find(header, "Content%-Length: (%d+)\r\n")
a = nil;b = nil
data = socket:recv(tonumber(len))
data = tonumber(data)
if (data > System.playerVer()) then --~~~(data > System.playerVer()) then
  textline("&rNew version available!")
  refresh()
  System.message("A new version is available:\n\n<LuaPlayer HM Ver. " .. data .. ">\n\nWould you like to Update?",1)
  button = System.buttonPressed(1)
  if button == "no" or button == "back" then
    socket:close()
    Wlan.term()
    textline("&rWLAN terminated.  Press start to quit.")
    refresh()
  else
    textline("Downloading updater script...")
    refresh()
    --sendheader(socket, "/updateplayer.lua")  --Moved this up above because of the ultra-low server timeout.
    header = ""
    while not string.find(header, "\r\n\r") do
      header = header .. socket:recv(2)
      screen.waitVblankStart()
    end
    if not string.find(header, "\r\n\r\n") then
      header = header .. socket:recv(1)
      screen.waitVblankStart()
    end
    a,b,len = string.find(header, "Content%-Length: (%d+)\r\n")
    a = nil;b = nil
    len = tonumber(len)
    file = io.open("/luaplayerupdate.lua", "wb")
    textline("&gDownloaded 0 bytes of " .. len .. "...")
    refresh()
    perc = 0
    while perc ~= "100%" do
      pos = file:seek("cur")
      changeline("&gDownloaded " .. pos .. " bytes of " .. len .. "...")
      refresh()
      perc = 100*pos/len
      pbar:clear(black)
      pbar:fillRect(0,0,perc*2,18,green)
      perc = tostring(math.floor(perc)) .. "%"
      x = 100 - (string.len(perc) * 4)
      for xo = -1,1 do
        for yo = -1,1 do
          pbar:print(x+xo, 5+yo, perc, black)
        end
      end
      pbar:print(x, 5, perc, white)
      refresh()
      --Yes, the socket is capable of this kind of speed.  I originally developed this script
      --using my home pc as the webserver and a large archive in place of the script.
      --The download whipped through at 13370 bytes at a time with no problem whatsoever.
      file:write(socket:recv(13370)) 
      refresh()
      file:flush()
      refresh()
    end
    socket:send("Thanks, server dude.")
    socket:close()
    textline("Download complete!")
    textline(hr)
    refresh()
    file:close()
    pbar:clear()
    textline("Download saved to memory stick.")
    textline("&rPress X to update or start to quit.")
    refresh()
    gotscript = true
  end
else
  socket:close()
  Wlan.term()
  textline("Your current version is up to date.")
  textline("&rPress start to quit.")
  refresh()
end

while true do
  pad = Controls.read()
  if pad:start() then break end
  if pad:cross() and gotscript then
    --The following declarations and functions are from the original update
    --script and are required for the downloaded script to run.
    white = Color.new(255, 255, 255)
    red = Color.new(255, 0, 0)
    green = Color.new(0, 255, 0)
    offscreen = Image.createEmpty(480, 272)
    offscreen:clear(Color.new(0, 0, 0))
    y = 0
    x = 0
    function graphicsPrint(text)
      for i = 1, string.len(text) do
        char = string.sub(text, i, i)
        if char == "\n" then
          y = y + 8
          x = 0
        elseif char ~= "\r" then
          offscreen:print(x, y, char, white)
          x = x + 8
        end
      end
      screen:blit(0, 0, offscreen)
      screen.waitVblankStart()
      screen.flip()
    end
    function graphicsPrintln(text)
      graphicsPrint(text .. "\n")
    end
    dofile("/luaplayerupdate.lua")
  end
  refresh()
end
System.Quit()

