-- 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 main table
-- plus ancillary tables for type-specific data

-- stash existing AWS creds in temporary table so that we can remake it
CREATE TABLE aws_tmp (id, access_key_id, secret_key_enc, nonce, created_at);

INSERT INTO aws_tmp 
SELECT randomblob(16), access_key_id, secret_key_enc, nonce, created_at
FROM credentials
ORDER BY created_at DESC
-- we only ever used one at a time in the past
LIMIT 1;

-- new master credentials table
DROP TABLE credentials;
CREATE TABLE credentials (
    -- id is a UUID so we can generate it on the frontend
    id BLOB UNIQUE NOT NULL,
    name TEXT UNIQUE NOT NULL,
    credential_type TEXT NOT NULL,
    is_default BOOLEAN NOT NULL,
    created_at INTEGER NOT NULL
);

-- populate with basic data from existing AWS credential
INSERT INTO credentials (id, name, credential_type, is_default, created_at)
SELECT id, 'default', 'aws', 1, created_at FROM aws_tmp;

-- new AWS-specific table
CREATE TABLE aws_credentials (
    id BLOB UNIQUE NOT NULL,
    access_key_id TEXT NOT NULL,
    secret_key_enc BLOB NOT NULL,
    nonce BLOB NOT NULL,
    FOREIGN KEY(id) REFERENCES credentials(id) ON DELETE CASCADE
);

-- populate with AWS-specific data from existing credential
INSERT INTO aws_credentials (id, access_key_id, secret_key_enc, nonce)
SELECT id, access_key_id, secret_key_enc, nonce
FROM aws_tmp;

-- done with this now
DROP TABLE aws_tmp;


-- SSH keys are the new hotness
CREATE TABLE ssh_credentials (
    id BLOB UNIQUE NOT NULL,
    algorithm TEXT NOT NULL,
    comment TEXT NOT NULL,
    public_key BLOB NOT NULL,
    private_key_enc BLOB NOT NULL,
    nonce BLOB NOT NULL,
    FOREIGN KEY(id) REFERENCES credentials(id) ON DELETE CASCADE
);
