view src/main/kotlin/name/blackcap/passman/MergeSubcommand.kt @ 11:c69665ff37d0

Add merge subcommand (untested).
author David Barts <n5jrn@me.com>
date Sat, 21 Jan 2023 15:39:42 -0800
parents 72619175004e
children a38a2a1036c3
line wrap: on
line source

package name.blackcap.passman

import org.apache.commons.cli.*
import java.sql.ResultSet
import java.util.*
import kotlin.system.exitProcess

class MergeSubcommand(): Subcommand() {
    private companion object {
        const val FORCE = "force"
        const val HELP = "help"
    }
    private lateinit var commandLine: CommandLine
    private lateinit var db: Database

    override fun run(args: Array<String>) {
        parseArguments(args)
        db = Database.open()
        doMerge()
    }

    private fun parseArguments(args: Array<String>) {
        val options = Options().apply {
            addOption("f", MergeSubcommand.FORCE, false, "Do not ask before overwriting.")
            addOption("h", MergeSubcommand.HELP, false, "Print this help message.")
        }
        try {
            commandLine = DefaultParser().parse(options, args)
        } catch (e: ParseException) {
            die(e.message ?: "syntax error", 2)
        }
        if (commandLine.hasOption(MergeSubcommand.HELP)) {
            HelpFormatter().printHelp("$SHORTNAME merge [options] other_database", options)
            exitProcess(0)
        }
        if (commandLine.args.isEmpty()) {
            die("expecting other database name", 2)
        }
        if (commandLine.args.size > 1) {
            die("unexpected trailing arguments", 2)
        }
    }

    private fun doMerge() {
        val otherFile = commandLine.args[0]
        val otherDb = Database.open(
            fileName = otherFile,
            passwordPrompt = "Key for ${see(otherFile)}: ", create = false
        )
        otherDb.connection.prepareStatement("select name, username, password, notes, created, modified, accessed from passwords").use { stmt ->
            val results = stmt.executeQuery()
            while (results.next()) {
                val otherEntry = makeEntry(results)
                val thisEntry = getEntry(db, otherEntry.name)
                if (thisEntry == null) {
                    doInsert(otherEntry)
                } else {
                    doCompare(thisEntry, otherEntry)
                    thisEntry.password.clear()
                }
                otherEntry.password.clear()
            }
        }
    }

    private fun makeEntry(results: ResultSet) = Entry(
        name = results.getDecryptedString(1, db.encryption)!!,
        username = results.getDecryptedString(2, db.encryption)!!,
        password = results.getDecrypted(3, db.encryption)!!,
        notes = results.getDecryptedString(4, db.encryption),
        created = results.getDate(5),
        modified = results.getDate(6),
        accessed = results.getDate(7)
    )

    private fun getEntry(otherDb: Database, name: String): Entry? {
        otherDb.connection.prepareStatement("select name, username, password, notes, created, modified, accessed from passwords where id = ?").use { stmt ->
            stmt.setLong(1, otherDb.makeKey(name))
            val results = stmt.executeQuery()
            return if (results.next()) makeEntry(results) else null
        }
    }

    private fun doInsert(entry: Entry) {
        db.connection.prepareStatement("insert into passwords (id, name, username, password, notes, created, modified, accessed) values (?, ?, ?, ?, ?, ?, ?, ?)")
            .use {
                it.setLong(1, db.makeKey(entry.name))
                it.setEncryptedString(2, entry.name, db.encryption)
                it.setEncryptedString(3, entry.username, db.encryption)
                it.setEncrypted(4, entry.password, db.encryption)
                it.setEncryptedString(5, entry.notes, db.encryption)
                it.setLongOrNull(6, entry.created?.time)
                it.setLongOrNull(7, entry.modified?.time)
                it.setLongOrNull(8, entry.accessed?.time)
                it.executeUpdate()
            }
    }

    private fun doCompare(thisEntry: Entry, otherEntry: Entry) {
        if (otherEntry.modifiedOrCreated.after(thisEntry.modifiedOrCreated) && okToChange(thisEntry, otherEntry)) {
            db.connection.prepareStatement("update passwords set name = ?, username = ?, password = ?, notes = ?, modified = ? where id = ?").use {
                it.setEncryptedString(1, otherEntry.name, db.encryption)
                it.setEncryptedString(2, otherEntry.username, db.encryption)
                it.setEncrypted(3, otherEntry.password, db.encryption)
                it.setEncryptedString(4, otherEntry.notes, db.encryption)
                it.setLong(5, otherEntry.modifiedOrCreated.time)
                it.setLong(6, db.makeKey(thisEntry.name))
                it.executeUpdate()
            }
        }
    }

    private fun okToChange(thisEntry: Entry, otherEntry: Entry): Boolean {
        if (commandLine.hasOption(MergeSubcommand.FORCE)) {
            return true
        }
        val REDACTED = "(redacted)"
        println("EXISTING ENTRY:")
        thisEntry.printLong(REDACTED)
        println()
        println("NEWER ENTRY:")
        otherEntry.printLong(REDACTED)
        println()
        val answer = name.blackcap.passman.readLine("OK to overwrite existing entry? ")
        println()
        return answer.trimStart().firstOrNull()?.uppercaseChar() in setOf('T', 'Y')
    }

}