#!/bin/sh -e

url_md5() {
  echo -n $1|md5sum|cut -d ' ' -f1
}

convert_rules() {
mkdir -p /tmp/rules/data
mkdir -p /tmp/rules/host

uclient-fetch -q --no-check-certificate $1 -O /tmp/adnew.conf

rulename=$(url_md5 $1)

if [ -f /tmp/adnew.conf ]; then
  if (grep -wq "address=" /tmp/adnew.conf) ; then
    cp /tmp/adnew.conf /tmp/rules/data/$rulename.conf
  elif (grep -wq -e"0.0.0.0" -e"127.0.0.1" /tmp/adnew.conf) ; then
    cp /tmp/adnew.conf /tmp/rules/host/$rulename.txt
  else
    cat /tmp/adnew.conf | grep ^\|\|[^\*]*\^$ | sed -e 's:||:address\=\/:' -e 's:\^:/0\.0\.0\.0:' > /tmp/rules/data/$rulename.conf
  fi
fi
rm -rf /tmp/adnew.conf
}

ARRAY=$(uci get adbyby.@adbyby[0].subscribe_url 2> /dev/null)

rm -rf /tmp/rules

i=1
for j in $ARRAY
do
  convert_rules $j
  i=`expr $i + 1`
done
