#! /bin/sh
# $OpenBSD: print-ports-index,v 1.13 2025/11/03 14:46:04 sthen Exp $
#
# Copyright (c) 2018 Marc Espie <espie@openbsd.org>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

# recreate index file, identical to /usr/ports/INDEX
set -e

if [ $# -ge 1 ]
then
    file=$1
else
    file=/usr/local/share/sqlports
fi
cat <<'EOSQL' |sqlite3 $file
-- in order for group_concat to sort, you must do it in two steps
with 
    d1 (d, p, t) as 
	(select 
	    distinct((case pkgspec when '' then '' else pkgspec||':' end)||_paths.fullpkgpath) as fd,
	    _depends.fullpkgpath, type
	from _depends join _paths on _Paths.Id=_depends.dependspath order by fd),
-- and now the part that's going to be used 3 times in the main request
    d2 as
	(select group_concat(d, ' ') as dlist, p, t
	from d1 group by p, t)
select fullpkgname, ports.fullpkgpath,
    (case prefix when '/usr/local' THEN '' else prefix end),
      comment,descr, maintainer,categories,
    libd.dlist, buildd.dlist, rund.dlist,


    case 1
    	when only_for_archs is null then
	    case 1
	    when not_for_archs is null
	    then 'any'
	    else '!'||not_for_archs
	    end
	else only_for_archs
	end,
    '?',
    (case lower(PERMIT_PACKAGE) when 'yes' then 'y' else 'n' end),
    (case lower(PERMIT_DISTFILES) when 'yes' then 'y' else 'n' end)
    from ports
    	left join d2 as libd on libd.p=ports.pathid and libd.t=0
    	left join d2 as buildd on buildd.p=ports.pathid and buildd.t=2
    	left join d2 as rund on rund.p=ports.pathid and rund.t=1
     	where ports.pathid in (select distinct canonical from _paths) 
	group by ports.fullpkgpath
	order by ports.fullpkgpath;
EOSQL
