BEGIN;

-- This script upgrades a PiAnoS 4.0-rc17 (or earlier) instance to 4.0.0
-- It is mostly concerned with removing the (built-in) NIJ plugin, copying the relevant
-- data to the now core schema.
-- The COMMIT has voluntarily been left off and YOU MUST type it in for the patch to be effective.
-- You will need to run `dbadmin.py resolve` afterwards to indicate that the schema is in sync
-- ** DO NOT TRY TO `sync` SINCE IT IS BROKEN AND IS LIKELY TO SCREW THE DB. USE THIS SCRIPT AND RUN `resolve` AFTERWARDS **

ALTER TABLE person ADD COLUMN last_login timestamptz;
ALTER TABLE person ADD COLUMN suitability_approach int;
ALTER TABLE person ADD COLUMN must_change_pwd boolean NOT NULL DEFAULT false;

CREATE OR REPLACE FUNCTION pianos4_update_remove_nij_plugin() RETURNS void AS $$
DECLARE
	usr RECORD;
BEGIN
	FOR usr IN (SELECT person.id, nij_person_data.value::int AS browser_check, survey_result.answer::int AS suitability_approach
				FROM person 
				LEFT OUTER JOIN nij_person_data ON person.id = nij_person_data.person AND nij_person_data.key = 'browser_check'
				LEFT OUTER JOIN survey_result ON person.id = survey_result.person AND survey_result.survey = 1 AND survey_result.question = 6) LOOP
		IF usr.browser_check = 1 THEN
			UPDATE person SET last_login = now() WHERE id = usr.id;
		END IF;
		IF usr.suitability_approach IN (1,2) THEN
			UPDATE person SET suitability_approach = usr.suitability_approach WHERE id = usr.id;
		ELSE
			UPDATE person SET suitability_approach = 2 WHERE id = usr.id;
		END IF;
	END LOOP;
	RETURN;
END;
$$ LANGUAGE plpgsql;

SELECT pianos4_update_remove_nij_plugin();
DROP FUNCTION pianos4_update_remove_nij_plugin();

ALTER TABLE person ALTER COLUMN suitability_approach SET NOT NULL;

DROP FUNCTION getUserIntroStep(int);

DROP TABLE survey_result;
DROP TABLE survey;
DROP TABLE nij_person_data;
