"""Add trigger to update IP

Revision ID: 884dcf0066bf
Revises: ba377c6bd1c2

"""

# revision identifiers, used by Alembic.
revision = '884dcf0066bf'
down_revision = 'ba377c6bd1c2'

from alembic import op

drop_query = """
    DROP TRIGGER IF EXISTS "voip_ip_changed" ON "netiface";
    DROP FUNCTION IF EXISTS "update_mediaserver_voip_ip" ();
"""


def upgrade():
    op.execute(drop_query)

    op.execute("""
        CREATE FUNCTION "update_mediaserver_voip_ip" ()
          RETURNS trigger AS
        $$
        DECLARE
            "new_address" text;
        BEGIN
            SELECT "address" INTO "new_address" FROM "netiface" WHERE "networktype" = 'voip' LIMIT 1;
            UPDATE "mediaserver"
            SET "voip_ip" = "new_address"
            WHERE "name" = 'default';

            RETURN NEW;
        END;
        $$
        LANGUAGE plpgsql;
    """)

    op.execute("""
        CREATE TRIGGER "voip_ip_changed"
            AFTER INSERT OR UPDATE OR DELETE ON "netiface"
            EXECUTE PROCEDURE "update_mediaserver_voip_ip"();
    """)


def downgrade():
    op.execute(drop_query)
