#!/bin/sh
progdir=`dirname "$0"`
tmpdir="/mnt/mmc/Roms/-THEMES/tmp"
tdir="/mnt/mmc/CFW/skin"
tname="$1"
base=`basename "$1" .zip`
basetmp=${base%-*}
exttname=${tname##*.}
setfile=/mnt/mmc/CFW/skin/settings.json

if [[ $exttname == "zip" ]] || [[ $exttname == "ZIP" ]]; then
	rm -rf $tmpdir
	mkdir -p $tmpdir
	unzip -o "$tname" -d $tmpdir
	find $tmpdir -name "__MACOSX" -type d | while read -r sdir
	do
		rm -rf "$sdir"
	done
	find $tmpdir -name "skin" -type d | while read -r sdir
	do
		rm -f "$sdir/.DS_Store"
		rm -f "$sdir/font.ttf"
		cp -rf "$sdir" /mnt/mmc/CFW/
	done
	find $tmpdir -name "lang" -type d | while read -r sdir
	do
		rm -f "$sdir/.DS_Store"
		cp -rf "$sdir" /mnt/mmc/CFW/
	done
	find $tmpdir -name "font" -type d | while read -r sdir
	do
		rm -f "$sdir/.DS_Store"
		cp -rf "$sdir" /mnt/mmc/CFW/
	done
	unzip -n $progdir/system.zip -d $tdir
	cp -f /mnt/mmc/CFW/skin/system/CORES.png /mnt/mmc/CFW/skin/system/-CORES.png
	cp -f /mnt/mmc/CFW/skin/system/THEMES.png /mnt/mmc/CFW/skin/system/-THEMES.png
	cp -f /mnt/mmc/CFW/skin/system/PDF.png /mnt/mmc/CFW/skin/system/-PDF.png
	cp -f /mnt/mmc/CFW/bin/font.ttf /mnt/mmc/CFW/font/Oswald-Regular.otf
	sed -i 's/"text-alignment": ".*"/"text-alignment": "left"/g' $setfile
	sed -i 's/"text-margin": .*/"text-margin": 322/g' $setfile
	rm -rf $tmpdir
	if grep -q "简体中文" /mnt/mmc/CFW/language.flag; then
		$progdir/printstr "主题、图标安装完成."
	else
		$progdir/printstr "The theme and icon have been installed."
	fi
	sleep 1
elif [[ $exttname == "sh" ]] || [[ $exttname == "SH" ]]; then
	$1
elif [[ $exttname == "gz" ]] || [[ $exttname == "GZ" ]]; then
	rm -f /mnt/mmc/CFW/os/boot_logo.flag
	mount -o remount,rw /misc
	cp -f "$1" /misc/boot_logo.bmp.gz
	mount -o remount,ro /misc
	if grep -q "简体中文" /mnt/mmc/CFW/language.flag; then
		$progdir/printstr "启动 logo 设置完成."
	else
		$progdir/printstr "Boot logo setting completed."
	fi
	sleep 2
elif [[ $exttname == "txt" ]] || [[ $exttname == "TXT" ]]; then
	colorinfo=`cat "$1"`
	location=${colorinfo%#*}
	color=${colorinfo#*#}
	case $location in
		1)
		sed -i 's/"color-active": ".*"/"color-active": "#'${color}'"/g' "/mnt/mmc/CFW/skin/settings.json"
		;;
		2)
		sed -i 's/"color-favorite-active": ".*"/"color-favorite-active": "#'${color}'"/g' "/mnt/mmc/CFW/skin/settings.json"
		;;
		3)
		sed -i 's/"color-inactive": ".*"/"color-inactive": "#'${color}'"/g' "/mnt/mmc/CFW/skin/settings.json"
		;;
		4)
		sed -i 's/"color-favorite-inactive": ".*"/"color-favorite-inactive": "#'${color}'"/g' "/mnt/mmc/CFW/skin/settings.json"
		;;
		5)
		sed -i 's/"color-guide": ".*"/"color-guide": "#'${color}'"/g' "/mnt/mmc/CFW/skin/settings.json"
		;;
		*)
	esac
	if grep -q "简体中文" /mnt/mmc/CFW/language.flag; then
		$progdir/printstr "文字颜色设置完成."
	else
		$progdir/printstr "Text color setting completed."
	fi
	sleep 2
else
	if grep -q "简体中文" /mnt/mmc/CFW/language.flag; then
		$progdir/printstr "不是支持的资源文件, 无法继续."
		else
		$progdir/printstr "Not a supported resource file, unable to continue."
	fi
	sleep 2
fi
sync
