##########################################################################
#
# pgAdmin 4 - PostgreSQL Tools
#
# Copyright (C) 2013 - 2021, The pgAdmin Development Team
# This software is released under the PostgreSQL Licence
#
##########################################################################

"""Initial database creation

Revision ID: fdc58d9bd449
Revises:
Create Date: 2017-03-13 11:15:16.401139

"""
import base64
import os

import config
import sqlalchemy as sa
from alembic import op
from flask import current_app
from flask_security import Security, SQLAlchemyUserDatastore
from flask_security.utils import encrypt_password
from pgadmin.model import db, User, Role
from pgadmin.setup import get_version
from pgadmin.setup import user_info

# revision identifiers, used by Alembic.
revision = 'fdc58d9bd449'
down_revision = None
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###

    if get_version() != -1:
        return

    email, password = user_info()

    op.create_table('version',
                    sa.Column('name', sa.String(length=32), nullable=False),
                    sa.Column('value', sa.Integer(), nullable=False),
                    sa.PrimaryKeyConstraint('name')
                    )
    op.create_table('user',
                    sa.Column('id', sa.Integer(), nullable=False),
                    sa.Column('email', sa.String(length=256), nullable=False),
                    sa.Column('password', sa.String(length=256), nullable=True),
                    sa.Column('active', sa.Boolean(), nullable=False),
                    sa.Column('confirmed_at', sa.DateTime(), nullable=True),
                    sa.PrimaryKeyConstraint('id'),
                    sa.UniqueConstraint('email')
                    )
    op.create_table('role',
                    sa.Column('id', sa.Integer(), nullable=False),
                    sa.Column('name', sa.String(length=128), nullable=False),
                    sa.Column('description', sa.String(length=256), nullable=False),
                    sa.PrimaryKeyConstraint('id'),
                    sa.UniqueConstraint('name')
                    )
    op.create_table('setting',
                    sa.Column('user_id', sa.Integer(), nullable=False),
                    sa.Column('setting', sa.String(length=256), nullable=False),
                    sa.Column('value', sa.String(length=1024), nullable=True),
                    sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
                    sa.PrimaryKeyConstraint('user_id', 'setting')
                    )
    op.create_table('roles_users',
                    sa.Column('user_id', sa.Integer(), nullable=True),
                    sa.Column('role_id', sa.Integer(), nullable=True),
                    sa.ForeignKeyConstraint(['role_id'], ['role.id'], ),
                    sa.ForeignKeyConstraint(['user_id'], ['user.id'], )
                    )
    op.create_table('servergroup',
                    sa.Column('id', sa.Integer(), nullable=False),
                    sa.Column('user_id', sa.Integer(), nullable=False),
                    sa.Column('name', sa.String(length=128), nullable=False),
                    sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
                    sa.PrimaryKeyConstraint('id'),
                    sa.UniqueConstraint('user_id', 'name')
                    )
    op.create_table('server',
                    sa.Column('id', sa.Integer(), nullable=False),
                    sa.Column('user_id', sa.Integer(), nullable=False),
                    sa.Column('servergroup_id', sa.Integer(), nullable=False),
                    sa.Column('name', sa.String(length=128), nullable=False),
                    sa.Column('host', sa.String(length=128), nullable=False),
                    sa.Column('port', sa.Integer(), nullable=False),
                    sa.Column('maintenance_db', sa.String(length=64), nullable=False),
                    sa.Column('username', sa.String(length=64), nullable=False),
                    sa.Column('ssl_mode', sa.String(length=16), nullable=False),
                    sa.ForeignKeyConstraint(['servergroup_id'], ['servergroup.id'], ),
                    sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
                    sa.PrimaryKeyConstraint('id')
                    )
    db.engine.execute("""
INSERT INTO "role"
VALUES(1, 'Administrators', 'pgAdmin Administrators Role')
        """)
    db.engine.execute("""
INSERT INTO "roles_users"
VALUES(1, 1);
    """)
    db.engine.execute("""
INSERT INTO "servergroup"
VALUES(1, 1, 'Servers')
""")

    current_salt = getattr(
        config, 'SECURITY_PASSWORD_SALT', base64.urlsafe_b64encode(
            os.urandom(32)
        ).decode()
    )
    if current_app.extensions.get('security') is None:
        current_app.config['SECURITY_PASSWORD_SALT'] = current_salt
        user_datastore = SQLAlchemyUserDatastore(db, User, Role)
        Security(current_app, user_datastore, register_blueprint=False)
    else:
        current_app.config['SECURITY_PASSWORD_SALT'] = current_salt
    setattr(config, 'SECURITY_PASSWORD_SALT', current_salt)
    password = encrypt_password(password)

    db.engine.execute("""
INSERT INTO "user"
    VALUES(1, '%s',
           '%s',
           1, NULL)
    """ % (email, password))
    db.engine.execute("""
INSERT INTO "version"
VALUES('ConfigDB', 2);
    """)
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('server')
    op.drop_table('servergroup')
    op.drop_table('roles_users')
    op.drop_table('setting')
    op.drop_table('role')
    op.drop_table('user')
    op.drop_table('version')
    # ### end Alembic commands ###
