with recursive x as ((select
    1 as level
    ,(select
        l2.line  
        || ',' ||
        coalesce(case
          when
            (((extract(isodow from now()) - 1) * 10000 + extract(hour from now()) * 100 + extract(minute from now()))::int <@ any(c2.day_z)
            and c2.fwd_enable = 'true')
            or
            (not (((extract(isodow from now()) - 1) * 10000 + extract(hour from now()) * 100 + extract(minute from now()))::int <@ any(c2.day_z))
            and c2.fwd_enable = 'false')
          then
            c2.fwd_to
        end, '') 
        || ':' ||
        coalesce(c2.timeout, 180)
      from
        lines l2
      left outer join
        cfwd c2
      on
        l2.company_id = c2.company_id
        and l2.line = c2.line
      where
        l2.company_id = c.id
        and l2.line = l.line
    ) dest_lines2
    ,c.name
    ,l.cfwd2
    ,array[l.id] as x_array
from
  companies c
  ,lines l   
where
  c.id = l.company_id
  and l.line = '%s'  
  and c.name = '%s')
union all
(select
    level + 1
    ,(select
        l2.line  
        || ',' ||
        coalesce(case
          when
            (((extract(isodow from now()) - 1) * 10000 + extract(hour from now()) * 100 + extract(minute from now()))::int <@ any(c2.day_z)
            and c2.fwd_enable = 'true')
            or
            (not (((extract(isodow from now()) - 1) * 10000 + extract(hour from now()) * 100 + extract(minute from now()))::int <@ any(c2.day_z))
            and c2.fwd_enable = 'false')
          then
            c2.fwd_to
        end, '') 
        || ':' ||
        coalesce(c2.timeout, 180)
      from
        lines l2
      left outer join
        cfwd c2
      on
        l2.company_id = c2.company_id
        and l2.line = c2.line
      where
        l2.company_id = c.id
        and l2.line = l.line
    ) dest_lines2
    ,c.name
    ,l.cfwd2
    ,x.x_array || array[l.id]
from
  x
  ,companies c
  ,lines l   
where
  c.id = l.company_id
  and l.line = x.cfwd2
  and c.name = x.name
  and l.id <> any(x.x_array)))
select * from x;
