def init_db(db):
    """
    Initializes the given database for use.

    This creates the base schema and applies migrations if necessary.

    :param db: the database to initialize
    """
    db.executescript(
        """
CREATE TABLE IF NOT EXISTS site (
    name TEXT PRIMARY KEY NOT NULL,
    remote TEXT NOT NULL,
    env TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS deployment (
    id INTEGER PRIMARY KEY NOT NULL,
    path TEXT NOT NULL,
    revision TEXT NOT NULL,
    date INTEGER NOT NULL,
    active INTEGER NOT NULL,
    present INTEGER NOT NULL DEFAULT 1
);

CREATE TABLE IF NOT EXISTS variable (
    id INTEGER PRIMARY KEY NOT NULL,
    name TEXT NOT NULL UNIQUE ON CONFLICT REPLACE,
    value TEXT NOT NULL
)
"""
        )
    db.execute('PRAGMA user_version')
    ver = db.fetchone()[0]
    if ver < 1:
        db.execute('ALTER TABLE site ADD COLUMN default_treeish TEXT')
    db.execute('PRAGMA user_version = 1')
