--#!lua
--[[
Filename: wget.lua
License: MIT

Copyright (c) 2013 Odd Strabo <oddstr13@openshell.no>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]

local function geturlcontent(url)
  local response = http.get(url)
  assert(response, "Unable to download from the specified url.")
  return response.readAll()
end

local function get(url, filename)
  assert(not fs.exists(filename), "The output file allready exists.")
  print("Downloading to '"..filename.."'...")
  local data = geturlcontent(url)
  local fh = fs.open(filename, "w")
  fh.write(data)
  fh.close()
  print("OK!")
end

local function run(url)
  local data = geturlcontent(url)
  print("Running downloaded file..")
  runtime = loadstring(data)
  setfenv(runtime, setmetatable({}, {__index = _G}))
  return runtime()
end

local function usage()
  print("wget <url> <filename> # Download file")
  print("wget -r <url>         # Execute code at url")
end

local argv = {...}
if argv[1] == "-r" and #argv == 2 then
  run(argv[2])
elseif #argv == 2 then
  get(argv[1], shell.resolve(argv[2]))
else
  usage()
end