Imports System
Imports System.IO

' Author:  derived
' Contact: derived888@gmail.com

Module StartupModule
    Private Const CONHDR_LEN = &HA000

    Public Function Main(ByVal CmdArgs() As String) As Integer
        Dim CONSign As New PackageAuth
        Dim CONHeader(CONHDR_LEN - 1) As Byte
        Dim fs_con As FileStream
        Dim CONFilename As String
        Dim KVFilename As String

        If CmdArgs.Count <> 2 Then
            System.Console.WriteLine("Wrong number of arguments")
            System.Console.WriteLine("Usage: CONSign <save to sign> <keyvault file to use>")
            Environment.Exit(1)
        End If

        System.Console.WriteLine("Processing file " & CmdArgs(0) & " using " & CmdArgs(1))

        CONFilename = CmdArgs(0)
        KVFilename = CmdArgs(1)

        ' open the save file
        Try
            fs_con = File.OpenRead(CONFilename)

            'check its length
            If fs_con.Length < CONHDR_LEN Then
                System.Console.WriteLine("Error: CON file """ & CONFilename & """ was incorrect length")
                Environment.Exit(1)
            End If

            fs_con.Read(CONHeader, 0, CONHDR_LEN)
            fs_con.Close()
        Catch ex As Exception
            System.Console.WriteLine("Error opening CON file " & CONFilename)
            Environment.Exit(1)
        End Try

        ' load the header
        If CONSign.LoadHeader(CONHeader) < 0 Then
            System.Console.WriteLine("Error processing CON file " & CONFilename & ": " & CONSign.GetError)
            Environment.Exit(1)
        End If

        ' load the keyvault
        If CONSign.LoadKeyVault(KVFilename) < 0 Then
            System.Console.WriteLine("Error loading keyvault " & KVFilename & ": " & CONSign.GetError)
            Environment.Exit(1)
        End If

        ' sign the header
        If CONSign.UpdateHeader(CONHeader) < 0 Then
            System.Console.WriteLine("Error signing CON file: " & CONSign.GetError)
            Environment.Exit(1)
        End If

        ' write the header
        Try
            fs_con = File.OpenWrite(CONFilename)
            fs_con.Write(CONHeader, 0, CONHeader.Length)
            fs_con.Close()
            System.Console.WriteLine("Done!")
        Catch ex As Exception
            System.Console.WriteLine("Error writing signed CON file back to disk, filename " & CONFilename)
            Environment.Exit(1)
        End Try

        Return 0
    End Function
End Module

