-- logout a user from a given phone
-- logoutuser(phone)
CREATE or REPLACE FUNCTION  logoutuser(integer) RETURNS integer AS '
   DECLARE
       phonereboot varchar;
       contactid integer;
       pw integer;
       worktime integer;
       pevent integer;
       pcontact integer;
       ch record; -- channel
   BEGIN
       -- should phones be rebooted? Normally yes.
       SELECT INTO phonereboot value from astglobals where name=''phonereboot'';

       -- who is currently logged in to this phone?
       SELECT INTO contactid id from contact where phone = $1 and status <> ''deleted'' limit 1;

       update contact set phone = 1 where phone = $1;
       update channel set inuse = ''no'' where phone = $1;
       update channel set inuse = ''yes'' where phone = $1 and line = ''1'';
       IF contactid IS NOT NULL THEN
         SELECT INTO pevent, worktime event, cast(extract(epoch FROM CURRENT_TIMESTAMP(0) - stamp) as integer) from contacthist 
               WHERE contact = contactid and event in (''40'', ''41'') order by stamp desc limit 1;
         if pevent = ''40'' THEN
           INSERT INTO contacthist (contact, stamp, event, int2, parm1) 
                  VALUES (contactid, CURRENT_TIMESTAMP(0), ''41'', worktime, ''Logoff'');
         END IF;
         RAISE NOTICE ''user % logged out'', contactid;
         INSERT INTO activate(action, type, which, status, created )
                VALUES (''modify'', ''contact'', contactid, ''QUEUED'', NOW() );
         INSERT INTO history (created, creator, contact, type, lookup, lookupid, value) values
               (NOW(), contactid, contactid, ''update'', ''phone'', $1, ''logged off'');
       END IF;
       INSERT INTO activate(action, type, which, status, created )
              VALUES (''modify'', ''phone'', $1, ''QUEUED'', NOW() );
       FOR ch IN select id from channel where phone = $1 LOOP
         INSERT INTO activate(action, type, which, status, created )
                VALUES (''modify'', ''channel'', ch.id, ''QUEUED'', NOW() );
       END LOOP;
       IF phonereboot = ''yes'' THEN
         INSERT INTO activate(action, type, which, status, created )
                VALUES (''module'', ''phone-check-sync'', $1, ''QUEUED'', NOW() );
       END IF;

       SELECT INTO pw pairedwith from phone where id = $1;
       SELECT INTO pcontact id from contact where phone = pw and status <> ''deleted'' limit 1;

       --IF pcontact > ''1'' THEN
       --  PERFORM logoutuser(pw);
       --END IF;
       return ''1'';
   END;
' LANGUAGE plpgsql;

-- login a user to a phone, returns the previous phone
-- loginuser(phone,user)
CREATE or REPLACE FUNCTION loginuser(integer,integer) RETURNS integer AS '
   DECLARE
       query varchar;
       phonereboot varchar;
       prevphone integer;
       pw integer;
       pt integer; -- phonetype
       comp integer; -- company
       curuser integer; -- current logged in user on this phone
       tmp integer;
       usecount integer;
       pl record; -- phoneline
       ch record; -- channel
   BEGIN
       -- should phones be rebooted? Normally yes.
       SELECT INTO phonereboot value from astglobals where name=''phonereboot'';

       -- see if someone is already logged in to this phone
       select into curuser id from contact where phone = $1;
       IF curuser > 1 THEN
         INSERT INTO history (created, creator, contact, type, lookup, lookupid, value) values
               (NOW(), $2, curuser, ''update'', ''phone'', $1, ''logged off'');
         update contact set phone = 1 where id = curuser;
         INSERT INTO activate(action, type, which, status, created )
                VALUES (''modify'', ''contact'', curuser, ''QUEUED'', NOW() );
       END IF;

       -- ok, get the previous phone she was logged in to
       select into prevphone phone from contact where id = $2;

       -- get the phonetype of the phone she is logging in to
       select into pt,comp phonetype,company from phone where id = $1;

       -- get id of phone, this phone is paired with
       select into pw pairedwith from phone where id = $1;

       -- Set new phone, set the active channels on that phone,
       -- insert activate record to recreate the provisioning files,
       -- and finally reboot the phone
       update contact set phone = $1 where id = $2;
       update channel set inuse = ''no'' where phone = $1;

       FOR pl IN select line from phoneline where function = ''contact'' and lookupid = $2 and status <> ''deleted'' LOOP
         query := ''UPDATE channel SET inuse = '' || quote_literal(''yes'') ||
                  '' WHERE phone = '' || quote_literal($1) || '' and line = '' || quote_literal(pl.line);
         -- raise notice ''query: %'', query;
         execute query;
       END LOOP;

       IF pw > ''1'' THEN
         PERFORM logoutuser(pw);
         FOR pl IN select line from phoneline where function = ''contact'' and lookupid = $2 and status <> ''deleted'' LOOP
           query := ''UPDATE channel SET inuse = '' || quote_literal(''yes'') ||
                    '' WHERE phone = '' || quote_literal(pw) || '' and line = '' || quote_literal(pl.line);
           -- raise notice ''query: %'', query;
           execute query;
         END LOOP;
       END IF;


       -- ensure that at least one channel is enabled, some phones refuse to start up without channels
       SELECT INTO usecount count(*) from channel where phone = $1 and inuse = ''yes'';
       IF usecount < ''1'' THEN
         update channel set inuse = ''yes'' where phone = $1 and line = ''1'';
       END IF;

       INSERT INTO contacthist (contact, stamp, event, parm1) 
              VALUES ($2, CURRENT_TIMESTAMP(0), ''40'', ''Logon'');
       RAISE NOTICE ''user % logged in to phone %'', $2, $1;
       INSERT INTO activate(action, type, which, status, created )
              VALUES (''modify'', ''phone'', $1, ''QUEUED'', NOW() );
       INSERT INTO history (created, creator, contact, type, lookup, lookupid, value) values
             (NOW(), $2, $2, ''update'', ''phone'', $1, ''logged on'');
       INSERT INTO activate(action, type, which, status, created )
              VALUES (''modify'', ''contact'', $2, ''QUEUED'', NOW() );
       FOR ch IN select id from channel where phone = $1 LOOP
         INSERT INTO activate(action, type, which, status, created )
                VALUES (''modify'', ''channel'', ch.id, ''QUEUED'', NOW() );
       END LOOP;
       IF phonereboot = ''yes'' THEN
         INSERT INTO activate(action, type, which, status, created )
                VALUES (''module'', ''phone-check-sync'', $1, ''QUEUED'', NOW() );
       END IF;

       -- Recreate provisioning files for the old phone (if there was one)
       -- and  reboot that phone as well
       IF prevphone <> ''1'' AND prevphone <> $1 THEN
         INSERT INTO history (created, creator, contact, type, lookup, lookupid, value) values
               (NOW(), $2, $2, ''update'', ''phone'', prevphone, ''logged off'');
         update channel set inuse = ''no'' where phone = prevphone;
         update channel set inuse = ''yes'' where phone = prevphone and line = 1;
         INSERT INTO activate(action, type, which, status, created )
                VALUES (''modify'', ''phone'', prevphone, ''QUEUED'', NOW() );
         FOR ch IN select id from channel where phone = prevphone LOOP
           INSERT INTO activate(action, type, which, status, created )
                  VALUES (''modify'', ''channel'', ch.id, ''QUEUED'', NOW() );
         END LOOP;
         IF phonereboot = ''yes'' THEN
           INSERT INTO activate(action, type, which, status, created )
                  VALUES (''module'', ''phone-check-sync'', prevphone, ''QUEUED'', NOW() );
         END IF;
       END IF;
       return prevphone;
   END;
' LANGUAGE plpgsql;
