#! /bin/sh
# [v2c] TinyCore専用の拡張作成スクリプト
# 2ちゃんねる専用ブラウザ
# 次のコマンドを実行してインストールして下さい
# sh v2c.install.sh
#
# ※注意※ 日本語TrueTypeフォント(ttf-monapoなど)をインストールして下さい

test ! -t 0 && exit
cd `dirname $0`
RUN_DIR=`pwd`

. /etc/init.d/tc-functions
LIST=`busybox --list`
for i in $LIST; do
	alias $i="busybox $i"
done

myinstall(){
	if [ ! -f "/usr/local/tce.installed/$1" ]; then
		if [ ! -f "/etc/sysconfig/tcedir/optional/$1.tcz" ]; then
			tce-load -w $1
		fi
		tce-load -i $1
	fi
}

relinf=`wget -q -O - "http://v2c.s50.xrea.com/relinf.txt" | grep Version`
v2cver=${relinf#*=}
[ -z "${v2cver}" ] && exit

distfile="V2C_${v2cver}_Setup_Linux.bin"
url="http://v2c.s50.xrea.com/${distfile}"
target="v2c.tcz"
deplist=""

builddep="squashfs-tools-4.x"
workdir="v2c"

for i in ${builddep}; do
	myinstall $i
done

if [ ! -f "${distfile}" ]; then
	wget "${url}"
fi
[ ! -f "${distfile}" ] && exit

[ -d "squashfs-root" ] && rm -rf "squashfs-root"
[ -d "${workdir}" ] && rm -rf "${workdir}"
mkdir -p "squashfs-root/usr/local/share/applications"
mkdir -p "squashfs-root/usr/local/bin"
mkdir -p "${workdir}"

cat << EOS | sh ${distfile}
y
n
EOS
mv "v2c" "squashfs-root/usr/local"

cat << EOS > "squashfs-root/usr/local/bin/v2c"
#!/bin/sh
V2C_DIR="/usr/local/v2c"
JAR=\`cat \${V2C_DIR}/launcher/v2cjar.txt\`
if [ ! -d "\${HOME}/.v2c/launcher" ]; then
	mkdir -p \${HOME}/.v2c/launcher
fi
cp -f \${V2C_DIR}/v2c \${HOME}/.v2c/
cp -f \${V2C_DIR}/launcher/v2cjar.txt \${HOME}/.v2c/launcher/
ln -sf \${V2C_DIR}/launcher/\${JAR} \${HOME}/.v2c/launcher/
ln -sf \${V2C_DIR}/jrel \${HOME}/.v2c/jrel
echo "-Dv2c.directory= " > \${HOME}/.v2c/launcher/v2cargs.txt
if [ -x "\${HOME}/.v2c/v2c" ]; then
	exec \${HOME}/.v2c/v2c \$@
fi
EOS
chmod a+x "squashfs-root/usr/local/bin/v2c"

v2cdir="/usr/local/v2c"
ficon=$v2cdir/v2cicon.png
dte0="squashfs-root/usr/local/share/applications/v2c.desktop"
> "$dte0"
echo "[Desktop Entry]" >> $dte0
echo "Version=1.0" >> $dte0
echo "Encoding=UTF-8" >> $dte0
echo "Name=V2C" >> $dte0
echo "GenericName=BBS Browser" >> $dte0
echo "Comment=Viewer/Writer for BBS like 2ch" >> $dte0
echo "Icon=$ficon" >> $dte0
echo "Exec=v2c" >> $dte0
echo "Terminal=0" >> $dte0
echo "Type=Application" >> $dte0
echo "Categories=Application;Network;Java;" >> $dte0
echo "X-FullPathIcon=$ficon" >> $dte0

[ -f "${target}" ] && rm -f "${target}"
mksquashfs "squashfs-root" "${target}" -all-root -b 4096
find "squashfs-root" ! -type d | sort | sed -e s#squashfs-root/## > "${target}.list"
md5sum "${target}" > "${target}.md5.txt"
if [ ! -z "${deplist}" ]; then
	> "${target}.dep"
	for i in ${deplist}; do
		echo "$i.tcz" >> "${target}.dep"
		myinstall $i
	done
fi

for i in ${target} ${target}.dep ${target}.md5.txt; do
	[ -f "$i" ] && cp -f "$i" "/etc/sysconfig/tcedir/optional"
done

[ -d "${workdir}" ] && rm -rf "${workdir}"
[ -d "squashfs-root" ] && rm -rf "squashfs-root"
echo "Done!"