#!/bin/sh
this_dir=`cd $(dirname $0) && pwd`
if [ "$#" -ne "2" ]; then
  #echo "usage: $0 product version"
  exit 1
fi

db=${this_dir}/policys.db

cnt=`${this_dir}/sqlite3 $db "select count(*) from product_alias where name=lower('$1')"`

if [ "$cnt" -eq "0" ]; then
  echo "none cpe found for product '$1'"
  exit 0
fi


#echo "$cnt cpe found for product '$1': `sqlite3 $db "select group_concat(cpe) from product_alias where name=lower('$1')"`"

cnt=`${this_dir}/sqlite3 $db "select count(*) from sqlite_master where type='table' and name='policys'"`

sql=`${this_dir}/sqlite3 $db "
select distinct group_concat(sql, ' union ') from
(
 select 'select vulid from (select distinct vulid, \"$2\" as ver, v.version as M from single s,version v where s.product='||pid||' and s.mv=v.id and ('
  ||group_concat('(('||sql||') and s.operation='||id||')', ' or ')||'))' as sql from (select o.id, o.sql, p.id as pid from operation o, product p, product_alias a, single s where s.product=p.id and s.operation=o.id and p.name=a.cpe and a.name=lower(\"$1\") group by o.id, p.name)
 union 
select 'select vulid from (select distinct vulid, \"$2\" as ver, lt.version as L, rt.version as R from double d left join version lt on d.lv=lt.id left join version rt on d.rv=rt.id where d.product='||pid||' and ('
  ||group_concat('(('||sql||') and d.operation='||id||')', ' or ')||'))' as sql from (select o.id, o.sql, p.id as pid from operation o, product p, product_alias a, double d where d.product=p.id and d.operation=o.id and p.name=a.cpe and a.name=lower(\"$1\") group by o.id, p.name)
)"`

#echo $sql
if [ "$cnt" -eq "0" ]; then
  ${this_dir}/sqlite3 $db "$sql"
else
 ${this_dir}/sqlite3 $db "select 'edr--start--'||p.cve||'--edr--'||p.name||'--edr--'||p.advice||'--edr--'||t.text from policys p left join policytype t on p.type=t.name  where p.id in($sql) "
  #|column -t -s '|'
fi
#sqlite3 $db "select 'total '||count(*) from ($sql)"
