-- app structure is changing - instead of passphrase/salt being per credential,
-- we now have a single app-wide key, which is generated by hashing the passphrase
-- with the known salt. To verify the key thus produced, we store a value previously
-- encrypted with that key, and attempt decryption once the key has been re-generated.

-- For migration purposes, we want convert the passphrase for the most recent set of
-- AWS credentials and turn it into the app-wide passphrase. The only value that we
-- have which is encrypted with that passphrase is the secret key for those credentials,
-- so we will just use that as the `verify_blob`. Feels a little weird, but oh well.
WITH latest_creds AS (
    SELECT *
    FROM credentials
    ORDER BY created_at DESC
    LIMIT 1
)

INSERT INTO kv (name, value)
SELECT 'salt', salt FROM latest_creds
UNION ALL
SELECT 'verify_nonce', nonce FROM latest_creds
UNION ALL
SELECT 'verify_blob', secret_key_enc FROM latest_creds;


-- Credentials are now going to be stored in a separate table per type of credential
CREATE TABLE aws_credentials (
    name TEXT UNIQUE NOT NULL,
    access_key_id TEXT NOT NULL,
    secret_key_enc BLOB NOT NULL,
    nonce BLOB NOT NULL,
    -- at some point we may want to offer to auto-rotate AWS keys,
    -- so let's make sure to keep track of when they were created
    created_at INTEGER NOT NULL
);

INSERT INTO aws_credentials (name, access_key_id, secret_key_enc, nonce, created_at)
SELECT 'default', access_key_id, secret_key_enc, nonce, created_at
FROM credentials
ORDER BY created_at DESC
LIMIT 1;

DROP TABLE credentials;


-- SSH keys are the new hotness
CREATE TABLE ssh_keys (
    name TEXT UNIQUE NOT NULL,
    public_key BLOB NOT NULL,
    private_key_enc BLOB NOT NULL,
    nonce BLOB NOT NULL,
    created_at INTEGER NOT NULL
);
