$debug

--DEBUGGING = 1

-- Installation file.
-- This will install the Touch 1 software, including Linux,
-- on a machine that already has DOS.
-- This script is ONLY run in DOS.

-------------------------------------------------- IsFile ----------
-- This tells us if a given file is a file.  If it is a directory or if it
-- doesn't exist, it returns nil.
--
function IsFile(theFile)
	local file, openErr;

	file,openErr = readfrom(theFile)
	if file == nil then -- file is not found
		return nil
	else	
		readfrom() -- close the file
		return 1
	end
end
	
--------------------------------------------------- RunningInLinux -----------
-- RunningInLinux reports the operating system running on the Touch 1. 

function RunningInLinux()
	return IsFile("/proc/version")
end

----------------------------------------------------- CheckContentsFile ---
function CheckContentsFile(sourceDir)
	local file, retVal
	-- Grab the disk number

	file = readfrom(sourceDir .. "contents.lst")
	if file ~= nil then
		retVal = tonumber(read())
	else
		retVal = 0
	end
	readfrom()	-- Close the contents file.
	return retVal
end

-------------------------------------------------------- AskForDisk -------
-- This function asks for a specific disk number.
-- It then waits for <enter> to be pressed. When the key is pressed, 
-- the function looks for the contents.lst file on the floppy disk and reads
-- the first line. The first line of the contents.lst file is a single int
-- that is the disk number. The disk number is compared to the desired disk
-- number and if they are the same, the function returns a 1. Otherwise, 
-- the function asks for the disk again. 

function RequireDisk(diskNum, sourceDir)
	local diskNumber = nil

	-- While it is not the one we are looking for, keep asking until we
	-- get the one we want or the user presses cancel.
	diskNumber = CheckContentsFile(sourceDir)
	while diskNumber ~= diskNum do
		print("\n\nInsert disk "..tostring(diskNum)..", and hit <Enter>: ")
		read() -- wait for them to hit the enter key
		diskNumber = CheckContentsFile(sourceDir)
		print("") -- a blank line to improve readability
		if (diskNumber == nil) or (diskNumber == 0) then
			print("Installation disk not in disk drive")
		elseif diskNumber ~= diskNum then
			print("Disk "..tostring(diskNumber).." is in disk drive.")
		end
	end
    return 1
end

--------------------------------------------- CheckHardwareType -------
--
-- CheckHardwareType reports the type of hardware the software is being 
-- installed on. it returns 1000 for old 1000V hardware and 1500 for 1500V
-- or newer 1000V hardware. 

function CheckHardwareType(testRevDir)
	local openRes, openErr 	-- The results of trying to open the ver.txt file go here
	local hwType			-- The type of hardware we are looking at (1000 | 1500)
	local execError

	-- testrev.exe puts the result of the call in c:\touch1\inst.ver by default
	execute("mkdir c:\\touch1") -- make sure the directory exists
	--execError = execute(testRevDir .. "\\testrev")
	--openRes, openErr = readfrom("c:\\touch1\\inst.ver")
	--if openRes == nil  then
	--	print("Error "..tostring(openErr).." while opening c:\\touch1\\inst.ver.")
	--	return openRes, openErr
	--else
	--	local typeText = read()
	--	hwType = tonumber(typeText)		 -- This forces a numeric conversion
	--end
	--readfrom()		-- Close the inst.ver file
	-- return hwType
	return 1500 -- testrev doesn't support PCI cards.
end

----------------------------------------------- MakeLinuxBat ----------
-- MakeLinuxBat uses a dos utility called "aefdisk" to decide which 
-- partition we will be installing on. Then it creates the correct
-- linux.bat file in the C:\linux directory.
function MakeLinuxBat()
	execute("c:\\lint\\aefdisk.exe 1 /show > c:\\lint\\part.txt")
	
	local res, openErr, theLine, partNum
	partNum = 4 -- default.  Most drives use this partition number.
	res, openErr = readfrom("c:\\lint\\part.txt")
	theLine  = read() -- read one line
	while theLine ~= nil do
		if nil ~= strfind(theLine, "%*%*") then
			partNum = tonumber(strsub(theLine,1,1)) -- extract the partition num
		end
		theLine  = read() -- read another line
	end
	readfrom()
	res, openErr = writeto("c:\\linux\\linux.bat")
	local runline
	runline = format("loadlin bzimage root=/dev/hda%d rw", tonumber(partNum))
	write(runline)
	writeto()
end	

---------------------------------------------- UnzipLinux -------------

function UnzipLinux()
	if IsFile("c:\\lint\\single.esp") then
		execute("del c:\\lint\\single.esp")
	end
	execute("c:\\lint\\esplink c:\\lint\\lint132 c:\\lint\\single.esp")
	print("\n\nMoving old files.  This may take several minutes, so be patient.\nDon't turn off the Touch 1.\n")
	execute("deltree /N /O c:\\linux.old")
	execute("rendir c:\\linux c:\\linux.old") -- attempt to rename old one
	execute("deltree /N /O c:\\linux") -- delete it if we didn't succeed
	print("\n\nInstalling Linux. This takes a long time. Don't turn off the Touch 1.\n")
	execute("c:\\lint\\unesp xy c:\\lint\\single C:\\ > c:\\junk.txt")
end

------------------------------------------------------- InstallLinux ------
-- 
-- It installs Linux

function InstallLinux()
	UnzipLinux()
	MakeLinuxBat()
end


------- zonk
function CopyFilesFromDisk(iDiskNum, sourceDir, destDir)
	-- The contents.lst file contains the names of all the files that need to 
	-- be installed off of this disk. The following repeat loop reads each
	-- file name and copies the file so named from the install disk to the 
	-- Touch 1. When we hit the end fo the file, read() will return a nil
	-- The contents.lst file also contains the checksums of all the files that
	-- need to be copied.  The file "checksum.exe"
	-- in DOS is included on the 1st disk.  Run it to make sure that all of the
	-- files are copied OK.
	local diskFileNumber = 0
	local diskFile = {}
	diskFile.name = {}
	diskFile.checksum = {}
	local fileNameLine, fileName
--print("debug Copy 1")
	local file = readfrom(sourceDir .. "contents.lst")
--print("debug Copy 1.5: "..tostring(file)..":"..sourceDir.."contents.lst")
	repeat
		fileNameLine = read()
--print("debug copy 1.6: "..tostring(fileNameLine))
		if fileNameLine ~= nil then
--print("debug Copy 2: "..fileNameLine)
			local commaPos = strfind(fileNameLine, ",")
			if commaPos == nil then
				if diskFileNumber ~= 0 then -- Not looking skipping disk #.
					print("contents.lst corrupt.\nGet new install disks.")
					return -91
				end
			else
				fileName = strsub(fileNameLine, 1, commaPos - 1) -- first part of fileNameLine
				fileCheckSum = tonumber(strsub(fileNameLine, commaPos+1)) -- last part of fileNameLine
				-- Copy the file from the floppy to the temp dir
				print("Copying file: " .. fileName)
				local theCmd = "copy "..sourceDir .. fileName.." "..destDir
--print("Debug Copy 2.1: "..theCmd)
				execute(theCmd)
				-- Add the file to the list of files copied
				diskFileNumber = diskFileNumber + 1
				diskFile.name[diskFileNumber] = fileName
				diskFile.checksum[diskFileNumber] = fileCheckSum
			end
		end
--print("debug Copy 3")
	until fileNameLine == nil
	readfrom() 	-- Close the contents.lst file.

	local iIndex = 1
	print("Now will check Checksums for all files on this disk.")
	while iIndex <= diskFileNumber do
		-- Check all the file checksums, now that we have the checksum program in the temp dir.
		local theCmd = "c:\\tmpinst\\checksum " .. destDir .. "\\" .. diskFile.name[iIndex] .. " > " .. destDir .. "\\temp"
		print("Checking health of: "..diskFile.name[iIndex])
		execute(theCmd)
		local res, openErr
		res, openErr = readfrom(destDir .. "\\temp")
		local checksum
		checksum = tonumber(read())
		readfrom() -- close the file
		if checksum ~= diskFile.checksum[iIndex] then
			print(diskFile.name[iIndex] .. " corrupt.\nGet new install disks.")
			return -91
		end
		iIndex = iIndex + 1 -- move on to next file
	end
	print("All files copied from this disk are OK.")
	return 1
end

-------------------------------------------------------- Main Program -----

----- Directory Declarations ----
finalDir = "c:\\touch1\\"
sourceDir = "a:\\"
tempDir = "c:\\tmpinst"
destDir = tempDir
lintDir = "c:\\lint"

abort = RunningInLinux()
if abort then
	print("This program must be run in DOS, not Linux.")
else
	execute("cls")
	print("This will install all of the Touch 1 files, including")
	print("Linux.  It will erase all prior setup (if any), but")
	print("will attempt to preserve any Touch 1 test files")
	print("that have been stored on the hard disk.")
	print("\nIf you are using networking, it will attempt to preserve your setup.")
	print("You should ignore warnings like:\n 'file not found' or 'unable to create directory'\n")
	print("during the installation process if the installation continues past the warning.\n")
	print("Do you want to proceed? (Y/N)")

	cpText = read()
	if (strfind(cpText, "y") ~= nil) or (strfind(cpText, "Y") ~= nil) then
		print("\nProceeding with installation.")
	else
		print("\nInstallation cancelled.")
		abort = 1
	end
end

if abort == nil then -- proceed with the installation
	execute("c:") -- run from drive C
	execute("cd \\") -- make sure we are in the root directory
	execute("chkdsk /F /B c:") -- make sure the hard disk is healthy
	execute("deltree /N tmpinst") -- make sure it is empty
	execute("deltree /N lint")
	execute("mkdir tmpinst")
	execute("mkdir tmpinst") -- We call this twice because deltree could force 1st call to fail.
	execute("mkdir lint")
	execute("mkdir lint")
	execute("mkdir touch1") -- does nothing if the directory already exists
	execute("mkdir touch1")
	if IsFile("touch1\\#") then
		execute("del touch1\\#") -- This does not delete it if it's a directory.
	end
	if IsFile("touch1\\data") then
		execute("del touch1\\data") -- This does not delete it if it's a directory.
	end
	-- We first copy all of the files from all of the disks into the tempDir.
	local iaDisks = {1, 2, 4, 5, 6}
	local iDiskIndex = 1
--print("debug 2")
	while iaDisks[iDiskIndex] ~= nil do
		local iDiskNum = iaDisks[iDiskIndex]
if DEBUGGING == 1 then
	sourceDir = "c:\\tempdir\\"..tostring(iDiskNum).."\\"
	print("Source dir is: "..sourceDir)
end
		RequireDisk(iDiskNum, sourceDir) -- ask for disk 1 until we get it
		local iErr
		if iDiskNum > 3 then
--print("debug 3.1")
			iErr = CopyFilesFromDisk(iDiskNum, sourceDir, lintDir) -- Linux files
		else
--print("debug 3.2")
			iErr = CopyFilesFromDisk(iDiskNum, sourceDir, destDir) -- Touch 1 files
		end
--print("debug 4")
		if iErr < 0 then
			abort = 1
			iDiskIndex = 999 -- Catastrophic failure.  Get out.
		end
		iDiskIndex = iDiskIndex + 1
	end
end
--print("debug 5")

if abort == nil then -- All files are successfully copied to the hard disk.
	print("All files have been successfully copied.")
	if 1500 ~= CheckHardwareType(destDir) then
		print("Old hardware type.  Install software version 2.55 or 3.191 from www.cirris.com")
		abort = 1
	end
end

if abort == nil then -- correct hardware type & files all ready to go.
	print("\n\n\n\n\nNow finalizing the installation.\n")
	execute("c:") -- Make sure we are executing from drive C since it'll be a temp disk as well as a dest disk.
	execute("copy "..destDir.."\\aefdisk.exe c:\\lint")
	InstallLinux()
	execute("rename c:\\config.sys c:\\config.dos") -- don't need this for Linux.
	execute("copy c:\\linux.old\\etc\\net.cfg c:\\linux\\etc") -- preserve network setup
	execute("copy "..destDir.."\\*.* c:\\touch1") -- copy Touch 1 files to where they go
	execute("copy c:\\touch1\\autoexec.bat c:\\")
	print("\n\nInstallation complete.  Reboot the Touch 1.")
end