-- define globals
global eudoraAttachmentsFolderName
global fileURLtoAttachmentsFolder
global importFolderName
global logFile
global logInterval
global pathToEudoraFolder
global pathToHome
global pathToMail
global pathToMailboxes



--define variables
set completeMailboxList to {}
set AppleScript's text item delimiters to ""
tell application "Finder" to set pathToHome to (home as string)
set logInterval to 10



--localization
set eudoraMailFolderName to "Mail Folder"
set eudoraAttachmentsFolderName to "Attachments Folder"



--set some defaults based on client name
set emailClient to "Eudora"
set importFolderName to "Eudora-Import"



--determine the version of Mac OS that is running
try
	get path to extensions
	activate
	display dialog "This script will only run on Mac OS X." buttons {"Quit"} default button 1
	return
on error
	tell application "Finder" to set pathToHome to (home as string)
	set pathToMail to pathToHome & ":Library:Mail:"
	set pathToMailboxes to pathToMail & "Mailboxes:"
end try



--main procedure
display dialog "To begin import of email from " & emailClient & ", you'll need to find the location where your email is stored." buttons {"Continue"} default button 1
display dialog "In the next screen, you'll be asked to navigate to the folder named 'Eudora Folder'. Here is where it is typically located:" & return & return & ¬
	"" & return & ¬
	"      Documents" & return & ¬
	"                Eudora Folder"
activate
set pathToEudoraFolder to (choose folder with prompt "Navigate to your 'Eudora Folder':")
set pathToEudoraMail to (pathToEudoraFolder as string) & eudoraMailFolderName & ":"
tell application "Finder"
	try
		set eudoraFolderContents to every item of alias pathToEudoraMail
		my createImportFolder()
		set importFolderLocation to alias (pathToMailboxes & importFolderName & ":")
		
		tell application "TextEdit"
			activate
			close every document saving ask
			make new document at the beginning of documents
			set the name of window 1 to importFolderName
			set text of document 1 to ¬
				"--- " & my displayTime() & ": Starting import from " & emailClient & " ---" & return & return & "Preparing mailboxes..." & return & return & ¬
				return & "--- Import in progress ---" & return
		end tell
		
		repeat with eachItem in eudoraFolderContents
			try
				duplicate (eachItem) to importFolderLocation
			end try
		end repeat
		my createAttachmentsFolder()
		my traverseEudoraFolders(importFolderLocation)
		my writeToLog("", 3)
		my writeToLog("", 4)
		my writeToLog("--- " & my displayTime() & ": Import finished! ---", 6)
		delete alias pathToErrorFile
		activate
		display dialog "Importing done! If Mail is already running, you need to quit and relaunch Mail." buttons {"OK"} default button 1
		set AppleScript's text item delimiters to ""
	on error errText
		display dialog errText
	end try
end tell



--handlers
on convertASCII(tempMboxFile, mboxFile)
	set AppleScript's text item delimiters to ""
	tell application "Finder"
		set theOriginalMbox to (open for access alias tempMboxFile)
		set theFinalMbox to (open for access alias mboxFile with write permission)
		set contentType to ""
		set contentTypeSuffix to ""
		set hasAttachments to 0
		set attachmentList to {}
		set newMessage to 1
		set eachLine to "Nil"
		set messageCounter to 0
		set currentMessage to ""
		set messageDone to 0
		set mailboxDone to 0
		repeat
			set previousLine to eachLine
			try
				set eachLine to read theOriginalMbox before return
			on error
				set messageDone to 1
				set mailboxDone to 1
			end try
			if (eachLine starts with "From ???@???") then
				set messageCounter to messageCounter + 1
				if newMessage is equal to 1 then
					set newMessage to 0
					set currentMessage to eachLine & (ASCII character 10)
				else
					set messageDone to 1
				end if
			else if (eachLine begins with "From ") then
				set eachLine to ">" & eachLine
			else if (eachLine begins with "Attachment Converted:") then
				set AppleScript's text item delimiters to ": "
				set attachmentBlob to text item 2 of eachLine
				set AppleScript's text item delimiters to ":"
				set fileinfoBlob to last text item of attachmentBlob
				set AppleScript's text item delimiters to " "
				set filenameBlob to first text item of fileinfoBlob
				set AppleScript's text item delimiters to ":"
				set filename to last text item of filenameBlob
				set attachmentList to attachmentList & filename
				set hasAttachments to 1
				set AppleScript's text item delimiters to ""
				set eachLine to ""
			else if (eachLine begins with "<") then
				set stringEnd to 1
				if (eachLine begins with "") then
					set contentType to "text/html"
					set stringEnd to 9
				else if (eachLine begins with "") then
					set stringEnd to 10
				else if (eachLine begins with "") then
					set stringEnd to 11
				else if (eachLine begins with "") then
					set stringEnd to 12
				else if (eachLine begins with "") then
					set contentType to "text/rich"
					set stringEnd to 9
				else if (eachLine begins with "") then
					set stringEnd to 10
				else if (eachLine begins with "") then
					set stringEnd to 22
				else if (eachLine begins with "") then
					set stringEnd to 23
				else if (eachLine begins with "") then
					set stringEnd to 13
				else if (eachLine begins with "") then
					set stringEnd to 9
				else if (eachLine begins with "") then
					set stringEnd to 10
				end if
				try
					set eachLine to (characters stringEnd thru -1 of eachLine) as string
				on error
					set eachLine to ""
				end try
			else if (eachLine begins with "Content-type: multi") then
				set semiColonOffset to offset of ";" in eachLine
				set boundaryOffset to offset of "boundary" in eachLine
				if (semiColonOffset is not equal to 0) then
					try
						set contentType to (characters (semiColonOffset + 1) thru -1 of eachLine) as string
					on error
						set contentType to ""
					end try
				else
					set contentType to "text/plain"
				end if
				if (boundaryOffset is not equal to 0) then
					set contentTypeSuffix to ""
				end if
				set eachLine to "nil"
			else if (eachLine begins with "Subject:") then
				try
					set messageSubject to (characters 10 thru -1 of eachLine) as string
				on error errText number errNum
					set messageSubject to ""
				end try
				if (messageCounter mod logInterval is equal to 0) then
					my writeToLog(("Message " & messageCounter as string) & ": " & messageSubject, 4)
				end if
			else if ((eachLine contains "boundary") and (previousLine begins with "Content-type: multi")) then
				set eachLine to "nil"
			else if (eachLine starts with "From ") then
				set eachLine to ">" & eachLine
			end if
			if (eachLine is not equal to "nil" and eachLine does not start with "From ???@???") then
				set currentMessage to currentMessage & eachLine & (ASCII character 10)
			end if
			if (messageDone is equal to 1) then
				if (contentType is equal to "") then
					write (currentMessage) to theFinalMbox starting at eof
				else
					set AppleScript's text item delimiters to ASCII character 10
					try
						set lineCounter to 1
						repeat
							set currentLine to text item lineCounter of currentMessage
							if (currentLine begins with "Subject:") then
								write currentLine & (ASCII character 10) & "Content-type: " & contentType & ¬
									contentTypeSuffix & (ASCII character 10) to theFinalMbox starting at eof
							else
								write currentLine & (ASCII character 10) to theFinalMbox starting at eof
							end if
							set lineCounter to lineCounter + 1
						end repeat
					end try
				end if
				set AppleScript's text item delimiters to ""
				if (hasAttachments is equal to 1) then
					write (ASCII character 10) & "This message has the following attachment(s):" & (ASCII character 10) to theFinalMbox starting at eof
					repeat with eachAttachment in attachmentList
						write "<< " & fileURLtoAttachmentsFolder & eachAttachment & " >>" & (ASCII character 10) to theFinalMbox starting at eof
					end repeat
					write ((ASCII character 10) & "Shortcut to Attachments folder:" & (ASCII character 10) & fileURLtoAttachmentsFolder) & (ASCII character 10) & (ASCII character 10) to theFinalMbox starting at eof
				end if
				set contentType to ""
				set hasAttachments to 0
				set attachmentList to {}
				set messageDone to 0
				set contentTypeSuffix to ""
				set currentMessage to eachLine & (ASCII character 10)
			end if
			if (mailboxDone is equal to 1) then
				exit repeat
			end if
		end repeat
		try
			close access theOriginalMbox
		end try
		try
			close access theFinalMbox
		end try
		delete alias tempMboxFile
		set AppleScript's text item delimiters to ""
		set temporaryFolder to (container of alias mboxFile)
		set temporaryFolderName to name of temporaryFolder
		set temporaryOffset to (offset of ".temporary" in temporaryFolderName)
		set newFolderName to ((characters 1 thru (temporaryOffset - 1) of temporaryFolderName) as string) & ".mbox"
		set name of temporaryFolder to newFolderName
	end tell
end convertASCII




on createAttachmentsFolder()
	tell application "Finder"
		set attachmentFolder to pathToMail & "Attachments:"
		if (alias attachmentFolder exists) then
		else
			make new folder at pathToMail with properties {name:"Attachments"}
		end if
		set pathToEudoraAttachments to (pathToEudoraFolder as string) & eudoraAttachmentsFolderName & ":"
		set eudoraAttachmentsFolderContents to every item of alias pathToEudoraAttachments
		repeat with eachItem in eudoraAttachmentsFolderContents
			try
				duplicate (eachItem) to alias attachmentFolder
			end try
		end repeat
		set startupDiskName to startup disk as string
		set homeDirectory to home as string
		set AppleScript's text item delimiters to ":"
		set pathToAttachmentsFolder to pathToMail & "Attachments:"
		if first text item of pathToAttachmentsFolder is equal to startupDiskName then
			set tempPath to text items 2 thru -1 of pathToAttachmentsFolder
		else
			set tempPath to "Volumes/" & every text item of pathToAttachmentsFolder
		end if
		set tempURL to every text item of tempPath
		set AppleScript's text item delimiters to "/"
		set tempFileURL to "file:///" & every text item of tempURL
		set AppleScript's text item delimiters to " "
		set URLtextItems to every text item of tempFileURL
		set AppleScript's text item delimiters to "%20"
		set fileURLtoAttachmentsFolder to every text item of URLtextItems as string
		set AppleScript's text item delimiters to ""
	end tell
end createAttachmentsFolder



on createImportFolder()
	tell application "Finder"
		if (alias pathToMail exists) then
		else
			make new folder at alias (pathToHome & ":Library:") with properties {name:"Mail"}
		end if
		if (alias pathToMailboxes exists) then
		else
			make new folder at alias (pathToMail) with properties {name:"Mailboxes"}
		end if
	end tell
	set safeImportFolderName to my makeUniqueName(importFolderName, pathToMailboxes)
	set importFolderName to safeImportFolderName
	tell application "Finder"
		make new folder at alias pathToMailboxes with properties {name:importFolderName}
		set pathToImportFolder to (pathToMailboxes & importFolderName)
	end tell
end createImportFolder



on displayTime()
	set currentDate to current date
	get time string of currentDate
	return the result
end displayTime



on makeUniqueName(proposedFile, proposedLocation)
	tell application "Finder"
		set mboxExtension to 0
		set dotPosition to (offset of ".mbox" in proposedFile) as number
		if (dotPosition is not equal to 0) then
			set mboxExtension to 1
			set namePrefix to ((characters 1 thru (dotPosition - 1) of proposedFile) as string)
		end if
		set success to 0
		set counter to 1
		set proposedName to proposedFile
		repeat until success is equal to 1
			set allNames to {}
			try
				set allNames to allNames & name of every file of alias proposedLocation
			end try
			try
				set allNames to allNames & name of every folder of alias proposedLocation
			end try
			if allNames contains proposedName then
				if (mboxExtension is equal to 1) then
					set proposedName to (namePrefix & " " & counter as string) & ".mbox"
				else
					set proposedName to proposedFile & " " & counter as string
				end if
				set counter to counter + 1
			else
				set success to 1
				return proposedName
			end if
		end repeat
	end tell
end makeUniqueName



on startingNewMailbox(savedMboxName)
	my writeToLog("", 4)
	set displayString to "Importing '" & savedMboxName & "'"
	my writeToLog(displayString, 3)
end startingNewMailbox



on traverseEudoraFolders(currentFolder)
	tell application "Finder"
		set completeMailboxList to (every file of currentFolder)
		repeat with eachItem in completeMailboxList
			set mboxFile to eachItem as string
			set savedMboxName to name of alias mboxFile
			set createLocation to container of alias mboxFile
			set name of alias mboxFile to savedMboxName & "Temp"
			make new folder at createLocation with properties {name:savedMboxName & ".temporary"}
			move alias (mboxFile & "Temp") to the result
			set tempMboxFile to (mboxFile & ".temporary:" & savedMboxName & "Temp")
			set mboxFile to mboxFile & ".temporary:mbox"
			set mboxCreateLocation to (createLocation as string) & ":" & savedMboxName & ".temporary:"
			make new file at alias (mboxCreateLocation) with properties {name:"mbox"}
			my startingNewMailbox(savedMboxName)
			my convertASCII(tempMboxFile, mboxFile)
		end repeat
		set subFolders to every folder of currentFolder
		repeat with eachFolder in subFolders
			my traverseEudoraFolders(eachFolder)
		end repeat
	end tell
end traverseEudoraFolders



on writeToLog(passedString, paragraphNumber)
	tell application "TextEdit"
		set paragraph paragraphNumber of text of document 1 to passedString & return
	end tell
end writeToLog