#!/bin/bash
#creates a zip version of a privoxy package suitable for android
#needs statically linked gentoo binary packages of privoxy and unscd
[ "$2" ]|| { echo "usage: $(basename $0) gentoo-privoxy-binary-pkg.tbz2 gentoo-unscd-binary-pkg.tbz2"; exit ; }


TMPDIR=/tmp/binary-pkg-to-zip-$RANDOM
OLD_PWD=$PWD
ZIP_PRIVOXY=$(basename "$1" .tbz2).zip
ZIP_UNSCD=$(basename "$2" .tbz2).zip

mkdir -p $TMPDIR/etc

for file in $@;do tar -xj -C $TMPDIR -f "$file";done
rm -r $TMPDIR/etc/{init.d,logrotate.d} $TMPDIR/usr/{lib,share/man}
sed -i \
	-e 's# /etc/# /sdcard/etc/#' \
	-e 's# /var/# /sdcard/var/#' \
	-e 's# /usr/# /sdcard/usr/#' \
		$TMPDIR/etc/privoxy/config
cat <<END > $TMPDIR/etc/resolv.conf
#Big, fast, commercial, tracking
#https://www.opendns.com/setupguide/
#nameserver 208.67.222.222
#https://developers.google.com/speed/public-dns/
#nameserver 8.8.8.8
#https://dns.yandex.com/
#nameserver 77.88.8.8

#ad blocking, commercial
#http://www.alternate-dns.com/
#nameserver 23.253.163.53

#censorshipfree (?), commercial (?)
#https://dns.watch
#nameserver 84.200.70.40
#https://freedns.zone
#nameserver 37.235.1.174
#http://servidordenoms.cat/vull-aquest-dns
#nameserver 109.69.8.51

#censorshipfree, open design/community driven (?)
#https://www.opennicproject.org/ (choose one near you)
#nameserver 185.97.7.7
#https://www.orsn.org/de/tech/pubdns/ (choose one near you)
nameserver 212.224.71.71
#https://digitalcourage.de/support/zensurfreier-dns-server
#nameserver 85.214.20.141
#https://blog.uncensoreddns.org/
#nameserver 91.239.100.100
END
echo "enable-cache	hosts	yes" > $TMPDIR/etc/nscd.conf
cat <<END >$TMPDIR/privoxy.start
#sdcard is mounted non-executable, so copy privoxy to the homedir of the used app
#Homedir of connectbot (change if a different app is used)
CB_HOME=/data/data/org.connectbot
[ /sdcard/usr/sbin/privoxy -nt \$CB_HOME/privoxy ] && cat /sdcard/usr/sbin/privoxy > \$CB_HOME/privoxy && chmod 755 \$CB_HOME/privoxy
#To enable caching of DNS queries, remove the '###' from these lines and make sure /sdcard/usr/sbin/unscd is present
###[ /sdcard/usr/sbin/unscd -nt \$CB_HOME/unscd ] && cat /sdcard/usr/sbin/unscd > \$CB_HOME/unscd && chmod 755 \$CB_HOME/unscd
###mkdir -p \$CB_HOME/var/run/nscd && \$CB_HOME/unscd -dd &
\$CB_HOME/privoxy --no-daemon /sdcard/etc/privoxy/config
#TODO: unscd -K does not kill all remaining workers, perhaps pkill should be added
###\$CB_HOME/unscd -K
END

cd $TMPDIR
zip -q -r $OLD_PWD/$ZIP_PRIVOXY * --exclude {usr/sbin/unscd,etc/nscd.conf}
zip -q $OLD_PWD/$ZIP_UNSCD usr/sbin/unscd etc/nscd.conf
cd $OLD_PWD

rm -r $TMPDIR
