-- Migrate database from version 2.1 to version 2.2
--
-- domain options
--
CREATE SEQUENCE domain_option_id_seq
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;

CREATE TABLE domain_option (
    domain_option_id integer DEFAULT nextval(('"domain_option_id_seq"'::text)::regclass) NOT NULL,
    domain_option_name character varying(50) NOT NULL
);

ALTER TABLE ONLY domain_option
    ADD CONSTRAINT pk_domain_option PRIMARY KEY (domain_option_id);

CREATE UNIQUE INDEX domain_option_name_idx ON domain_option USING btree ( domain_option_name );
    
CREATE TABLE domain__domain_option (
	domain_option_id integer NOT NULL,
	domain_id integer NOT NULL
); 

ALTER TABLE ONLY domain__domain_option
    ADD CONSTRAINT pk_domain__domain_option PRIMARY KEY (domain_option_id, domain_id);

ALTER TABLE ONLY domain__domain_option
    ADD CONSTRAINT domain_option_id_fkey FOREIGN KEY (domain_option_id) 
    	REFERENCES domain_option(domain_option_id) DEFERRABLE;

ALTER TABLE ONLY domain__domain_option
    ADD CONSTRAINT domain_id_fkey FOREIGN KEY (domain_id) 
    	REFERENCES domain(domain_id) DEFERRABLE;

--
-- table: domain_option
--
INSERT INTO domain_option (domain_option_name) 
	VALUES ('backupmxforexternalmx');
INSERT INTO domain_option (domain_option_name) 
	VALUES ('greylisting');
INSERT INTO domain_option (domain_option_name)
	VALUES ('htdocsfallback');
INSERT INTO domain_option (domain_option_name) 
	VALUES ('includes');
INSERT INTO domain_option (domain_option_name) 
	VALUES ('indexes');
INSERT INTO domain_option (domain_option_name)
	VALUES ('multiviews');
--
-- new domain options settings
--
-- existing default = ON
--
INSERT INTO domain__domain_option 	SELECT domain_option_id, domain_id
	FROM domain, domain_option
	WHERE domain_option.domain_option_name = 'greylisting' ;
INSERT INTO domain__domain_option SELECT domain_option_id, domain_id
	FROM domain, domain_option
	WHERE domain_option.domain_option_name = 'htdocsfalback' ;
INSERT INTO domain__domain_option SELECT domain_option_id, domain_id
	FROM domain, domain_option
	WHERE domain_option.domain_option_name = 'includes' ;
INSERT INTO domain__domain_option SELECT domain_option_id, domain_id
	FROM domain, domain_option
	WHERE domain_option.domain_option_name = 'indexes' ;
INSERT INTO domain__domain_option SELECT domain_option_id, domain_id
	FROM domain, domain_option
	WHERE domain_option.domain_option_name = 'multiviews' ;
--
-- existing default = OFF
--
DELETE FROM domain__domain_option USING domain_option
	WHERE domain__domain_option.domain_option_id = domain_option.domain_option_id
		AND domain_option.domain_option_name = 'backupmxforexternalmx' ;
--
-- End of migratino to version 2.2
--
