CREATE OR REPLACE FUNCTION match_firstchar(str text, chr text) RETURNS boolean AS $$
  SELECT CASE WHEN chr = '0'
         THEN (ascii(str) < 97 OR ascii(str) > 122) AND (ascii(str) < 65 OR ascii(str) > 90)
         ELSE ascii(str) IN(ascii(chr),ascii(upper(chr)))
         END;
$$ LANGUAGE SQL IMMUTABLE;


ALTER TABLE packages DROP CONSTRAINT packages_system_fkey;
ALTER TABLE packages ADD CONSTRAINT packages_system_fkey FOREIGN KEY (system) REFERENCES systems(id) ON DELETE CASCADE ON UPDATE CASCADE;

-- Remapping system IDs so we can sort on that rather than 'relorder'
-- (Yes, this means adding a new system somewhere in-between requires changing
-- system IDs again, but that's fine, these IDs are only used internally)
BEGIN;
WITH map(old,new) AS (
    -- FreeBSD
          SELECT  80,  84
    UNION SELECT  84,  80
    UNION SELECT 132,  99
    UNION SELECT  99, 129
    UNION SELECT 129, 132
    UNION SELECT 188, 198
    UNION SELECT 192, 188
    UNION SELECT 198, 203
    UNION SELECT 203, 192
    -- CentOS
    UNION SELECT 175, 176 
    UNION SELECT 176, 177 
    UNION SELECT 177, 178 
    UNION SELECT 178, 179 
    UNION SELECT 179, 182 
    UNION SELECT 182, 183 
    UNION SELECT 183, 175 
    UNION SELECT 195, 200 
    UNION SELECT 196, 201 
    UNION SELECT 200, 195 
    UNION SELECT 201, 206 
    UNION SELECT 206, 196 
) UPDATE systems SET id = new+10000 FROM map WHERE id = old;
UPDATE systems SET id = id-10000 WHERE id >= 10000;
COMMIT;

ALTER TABLE systems DROP COLUMN relorder;
