-- $debug

iMarkedExecutable = nil
function GetChecksum(fileName)
	if iMarkedExecutable == nil then	-- Make sure checksum is an executable
		execute("chmod +x /DOS/touch1/checksum")
        iMarkedExecutable = 1
	end
	execute("/DOS/touch1/checksum " .. fileName .. " > /tmp/temp")
	local res, openErr
	res, openErr = readfrom("/tmp/temp")
	local checksum = tonumber(read())
	readfrom() -- close the file
	execute("rm /tmp/temp")
    return tonumber(checksum)
end

-- We need to make sure that the program "chmod" is healthy.
if GetChecksum("/bin/chmod") ~= 43464 then
	if GetChecksum("/DOS/touch1/chmod") == 43464 then
        execute("chmod +x /DOS/touch1/chmod")	-- Use original chmod to make this one executable
    	execute("mv /bin/chmod /bin/chmod.bad") -- rename old one
        execute("cp /DOS/touch1/chmod /bin/chmod") -- copy new one
	end
end

execute("sync")	-- make sure all changes are flushed to disk
-- There may be packed files we need to extract.
execute("cd /DOS/touch1; ls -1 *.tgz > /tmp/tgz ; sync")
readfrom("/tmp/tgz")
theName = read()

local backup_lastlearned = 0
if (theName ~= nil) then
        backup_lastlearned = 1
end

if (theName ~= nil) and (strlen(theName) > 0) then
	execute("chmod +w /DOS/touch1/* ; sync")	-- make sure all files are writable
	execute("mkdir /tmp/un_tgz ; sync")  -- create dir, if it doesn't exist
	execute("rm -f /tmp/un_tgz/* ; sync") -- remove any prior temp files
end

if (backup_lastlearned) then
        execute("mv /DOS/touch1/lastlrnd /DOS/touch1/~lastlrnd_backup")
end

while (theName ~= nil) and (strlen(theName) > 0) do
	execute("cp /DOS/touch1/" .. theName .. " /tmp/un_tgz; sync")
    execute("cd /tmp/un_tgz; gzip -d " .. theName .."; tar -xf *; rm *.tar; sync")
    execute("cp /tmp/un_tgz/* /DOS/touch1; sync")
	execute("rm -f /tmp/un_tgz/*; sync") -- remove the temp files
	execute("rm /DOS/touch1/" .. theName.."; sync")
	theName = read()
end

if (backup_lastlearned) then
        execute("mv /DOS/touch1/~lastlrnd_backup /DOS/touch1/lastlrnd")
end

readfrom()	-- close the file list
-- execute("rmdir /tmp/un_tgz; sync") Removing directories CORRUPTS FILE SYSTEM
execute("rm /tmp/tgz")

-- Make formatting disks possible
execute("chmod +x /usr/bin/fdformat")
execute("chmod +x /sbin/mkdosfs")

-- This makes shift-tab be the inverse of tab.
-- You can alt-tab and shift-tab to back-up when
-- hitting tab to select the next button on the screen.

execute("chmod +x /DOS/touch1/loadkeys")
execute("/DOS/touch1/loadkeys /DOS/touch1/newkmap.map")
execute("sync")	-- make sure all changes are flushed to disk

