-- 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;
       comp integer; -- company
       need_lic_check varchar; -- need license checking?
       _lic_per_company varchar; -- count per company licences?
       _lic_used integer; -- current amount of used licenses
       _licenses integer; -- assigned amount of used licenses
       curuser integer; -- current logged in user on this phone
       tmp integer;
       usecount integer;
       worktime integer;
       pl record; -- phoneline
       ch record; -- channel
   BEGIN
       -- should phones be rebooted? Normally yes.
       SELECT INTO phonereboot value from astglobals where name=''phonereboot'';

       -- set this default to yes
       need_lic_check := ''yes'';

       -- get basic information 
       select into curuser id from contact where phone = $1;
       select into comp company from contact where id = $2;

       -- see if someone is already logged in to this phone
       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() );
         need_lic_check := ''no'';
       END IF;

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

       IF NOT FOUND THEN
         raise notice ''% logged on on another phone and cannot logout'', $2;
         return ''0'';
       END IF;

       -- if found (so switching to another phone) write a Logoff record for that phone
       IF prevphone <> 1 THEN
         SELECT INTO worktime cast(extract(epoch FROM CURRENT_TIMESTAMP(0) - stamp) as integer) from contacthist
               WHERE contact = $2 and event = ''40'' order by stamp desc limit 1;
         if FOUND THEN
           raise notice ''found logon for user %'', $2;
           INSERT INTO contacthist (contact, stamp, event, int2, parm1)
                  VALUES ($2, CURRENT_TIMESTAMP(0), ''41'', worktime, ''Logoff'');
         ELSE
           raise notice ''logon for user % not found'', $2;
         END IF;
         need_lic_check := ''no'';
       END IF;

       -- check license count
       if need_lic_check = ''yes'' THEN
         raise notice ''Need licenses check company %'', comp;
         select into _lic_per_company value from astglobals where name = ''lic_per_company'';
         -- are licenses set per company?
         IF _lic_per_company = ''yes'' THEN
           raise notice ''licenses set per company'';
           select into _licenses licenses from company where id = comp;
           select into _lic_used count(*) from contact where phone > 1 and company = comp and status != ''deleted'';
           raise notice ''used = %, max = %'', _lic_used, _licenses;
           IF _lic_used >= _licenses THEN
             raise notice ''% cannot login: license error'', $2;
             return ''-1'';
           END IF;
         END IF;
         SELECT INTO _licenses value FROM astglobals WHERE name = ''licusers'';
         SELECT INTO _lic_used count(*) as count FROM contact WHERE phone > 1 and status != ''deleted'';
         IF _lic_used >= _licenses THEN
           raise notice ''% cannot login: license error'', $2;
           return ''-1'';
         END IF;
       END IF;

       -- 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;

       -- give this phone as much channels as the user has extensions
       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;

       -- 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;

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

       IF pw > ''1'' THEN
         -- logout whoever is on the paired phone
         PERFORM logoutuser(pw);

         -- give this phone as much channels as the user has extensions
         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;
         -- ensure that at least one channel is enabled, some phones refuse to start up without channels
         update channel set inuse = ''no'' where phone = pw;
         SELECT INTO usecount count(*) from channel where phone = pw and inuse = ''yes'';
         IF usecount < ''1'' THEN
           update channel set inuse = ''yes'' where phone = pw and line = ''1'';
         END IF;
       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;

