Option Explicit

Const ForWriting = 2

Dim fso
Dim shell
Dim sourceFolder
Dim installFolder
Dim openCommand
Dim editCommand
Dim daemonPath
Dim candidates
Dim item
Dim configFile

Set fso = CreateObject("Scripting.FileSystemObject")
Set shell = CreateObject("WScript.Shell")

sourceFolder = fso.GetParentFolderName(WScript.ScriptFullName)
installFolder = "C:\LCGDiscLink"

If Not fso.FolderExists(installFolder) Then
    fso.CreateFolder installFolder
End If

On Error Resume Next
fso.CopyFile sourceFolder & "\LCGDiscLink.vbs", installFolder & "\LCGDiscLink.vbs", True
fso.CopyFile sourceFolder & "\LCGDiscLink.ico", installFolder & "\LCGDiscLink.ico", True

If Err.Number <> 0 Then
    MsgBox "Setup could not copy the LCG DiscLink files to C:\LCGDiscLink.", 16, "LCG DiscLink Setup"
    WScript.Quit 1
End If
On Error GoTo 0

openCommand = "wscript.exe " & Chr(34) & installFolder & "\LCGDiscLink.vbs" & Chr(34) & _
              " " & Chr(34) & "%1" & Chr(34)
editCommand = "notepad.exe " & Chr(34) & "%1" & Chr(34)

On Error Resume Next
shell.RegWrite "HKCR\.lcgdisc\", "LCGDiscLink.File", "REG_SZ"
shell.RegWrite "HKCR\LCGDiscLink.File\", "LCG RetroCloud Disc Link", "REG_SZ"
shell.RegWrite "HKCR\LCGDiscLink.File\DefaultIcon\", installFolder & "\LCGDiscLink.ico", "REG_SZ"
shell.RegWrite "HKCR\LCGDiscLink.File\shell\", "open", "REG_SZ"
shell.RegWrite "HKCR\LCGDiscLink.File\shell\open\", "Mount RetroCloud Disc", "REG_SZ"
shell.RegWrite "HKCR\LCGDiscLink.File\shell\open\command\", openCommand, "REG_SZ"
shell.RegWrite "HKCR\LCGDiscLink.File\shell\edit\", "View DiscLink File", "REG_SZ"
shell.RegWrite "HKCR\LCGDiscLink.File\shell\edit\command\", editCommand, "REG_SZ"

If Err.Number <> 0 Then
    MsgBox "Setup could not create the Windows file association.", 16, "LCG DiscLink Setup"
    WScript.Quit 1
End If
On Error GoTo 0

daemonPath = ""
candidates = Array( _
    "C:\Program Files\D-Tools\daemon.exe", _
    "C:\Program Files\DAEMON Tools\daemon.exe", _
    "C:\Program Files\DAEMON Tools 3.47\daemon.exe", _
    "C:\D-Tools\daemon.exe", _
    "C:\DAEMON Tools\daemon.exe")

For Each item In candidates
    If fso.FileExists(item) Then
        daemonPath = item
        Exit For
    End If
Next

If daemonPath <> "" Then
    Set configFile = fso.OpenTextFile(installFolder & "\daemon-path.txt", ForWriting, True)
    configFile.WriteLine daemonPath
    configFile.Close
End If

MsgBox "LCG DiscLink was installed successfully." & vbCrLf & vbCrLf & _
       "Double-click any .lcgdisc file to mount its real disc image with DAEMON Tools." & vbCrLf & vbCrLf & _
       "Restart Windows if the new disc icon does not appear immediately.", _
       64, "LCG DiscLink Setup"
