BEGIN;

--
-- Add ports information on partners
--

DO $$
BEGIN
    BEGIN
        ALTER TABLE partners ADD COLUMN port_r66 integer DEFAULT 6666;
    EXCEPTION
        WHEN duplicate_column THEN
        -- do nothing
    END;
END;
$$;

DO $$
BEGIN
    BEGIN
        ALTER TABLE partners ADD COLUMN port_r66_ssl integer DEFAULT 6667;
    EXCEPTION
        WHEN duplicate_column THEN
        -- do nothing
    END;
END;
$$;

DO $$
BEGIN
    BEGIN
        ALTER TABLE partners ADD COLUMN port_r66_monitoring integer DEFAULT 8066;
    EXCEPTION
        WHEN duplicate_column THEN
        -- do nothing
    END;
END;
$$;

DO $$
BEGIN
    BEGIN
        ALTER TABLE partners ADD COLUMN port_r66_admin integer DEFAULT 8067;
    EXCEPTION
        WHEN duplicate_column THEN
        -- do nothing
    END;
END;
$$;

DO $$
BEGIN
    BEGIN
        ALTER TABLE partners ADD COLUMN port_r66_rest integer DEFAULT 8088;
    EXCEPTION
        WHEN duplicate_column THEN
        -- do nothing
    END;
END;
$$;

DO $$
BEGIN
    BEGIN
        ALTER TABLE partners ADD COLUMN port_gwftp integer DEFAULT 6621;
    EXCEPTION
        WHEN duplicate_column THEN
        -- do nothing
    END;
END;
$$;

DO $$
BEGIN
    BEGIN
        ALTER TABLE partners ADD COLUMN port_gwftp_monitoring integer DEFAULT 8068;
    EXCEPTION
        WHEN duplicate_column THEN
        -- do nothing
    END;
END;
$$;


DO $$
BEGIN
    BEGIN
        ALTER TABLE partners ADD COLUMN port_gwftp_admin integer DEFAULT 8069;
    EXCEPTION
        WHEN duplicate_column THEN
        -- do nothing
    END;
END;
$$;

DO $$
BEGIN
    BEGIN
        ALTER TABLE partners ADD COLUMN port_gwftp_passive_min integer DEFAULT 30000;
    EXCEPTION
        WHEN duplicate_column THEN
        -- do nothing
    END;
END;
$$;

DO $$
BEGIN
    BEGIN
        ALTER TABLE partners ADD COLUMN port_gwftp_passive_max integer DEFAULT 40000;
    EXCEPTION
        WHEN duplicate_column THEN
        -- do nothing
    END;
END;
$$;

--
-- Add partner_data information on partners
--

DO $$
BEGIN
    BEGIN
        ALTER TABLE partners ADD COLUMN additional_data json NOT NULL DEFAULT '{}';
    EXCEPTION
        WHEN duplicate_column THEN
        -- do nothing
    END;
END;
$$;

DO $$
BEGIN
    BEGIN
        UPDATE partners SET additional_data=COALESCE(
            json_object(
                (SELECT array_agg(name::text) FROM partner_data
                 WHERE partners.id =partner_data.partner_id),
                (SELECT array_agg(value::text) FROM partner_data
                 WHERE partners.id =partner_data.partner_id)),
            '{}');
    EXCEPTION
        WHEN undefined_table THEN
            RAISE NOTICE 'Data migration already done';
    END;
END;
$$;


DROP TABLE IF EXISTS partner_data;

COMMIT;
