#!/bin/sh
kpfolder="/usr/share/koolproxy/data"
kplogfile="/var/log/koolproxy.log"
readyfolder="/tmp/upload/koolproxy"

backup() {
	if [ ! -f $kpfolder/private/ca.key.pem ]; then
		echo "未找到ca.key.pem，请先运行Koolproxy一次！" > $kplogfile
		exit 1
	fi
	if [ ! -f $kpfolder/private/base.key.pem ]; then
		echo "未找到base.key.pem，请先运行Koolproxy一次！" > $kplogfile
		exit 1
	fi
	if [ ! -f $kpfolder/certs/ca.crt ]; then
		echo "未找到ca.crt，请先运行Koolproxy一次！" > $kplogfile
		exit 1
	fi

	mkdir -p /tmp/upload
	cd $kpfolder
	tar czf /tmp/upload/koolproxyca.tar.gz private/ca.key.pem private/base.key.pem certs/ca.crt 
	[ -f /tmp/upload/koolproxyca.tar.gz ] && echo "证书备份已成功生成。" > $kplogfile 
}

restore() {
	if [ ! -f /tmp/upload/koolproxyCA.tar.gz ]; then
		echo "未找到备份文件，文件名必须为koolproxyCA.tar.gz或已损坏，请检查备份文件！" >> $kplogfile
	else
		mkdir -p $readyfolder
		cd $readyfolder
		tar xzf /tmp/upload/koolproxyCA.tar.gz
	fi
	if [ ! -f $readyfolder/private/ca.key.pem ]; then
		echo "未找到ca.key.pem,备份文件不正确或已损坏，请检查备份文件！" > $kplogfile
		exit 1
	fi
	if [ ! -f $readyfolder/private/base.key.pem ]; then
		echo "未找到base.key.pem，备份文件不正确或已损坏，请检查备份文件！" > $kplogfile
		exit 1
	fi
	if [ ! -f $readyfolder/certs/ca.crt ]; then
		echo "未找到ca.crt，备份文件不正确或已损坏，请检查备份文件！" > $kplogfile
		exit 1
	fi

	mv -f $readyfolder/private/ca.key.pem $kpfolder/private/ca.key.pem
	mv -f $readyfolder/private/base.key.pem $kpfolder/private/base.key.pem
	mv -f $readyfolder/certs/ca.crt $kpfolder/certs/ca.crt
	rm -rf $readyfolder
	rm -f /tmp/upload/koolproxyCA.tar.gz
	echo "证书成功还原，重启Koolproxy。" > $kplogfile 
	/etc/init.d/koolproxy restart
}

case "$*" in
	"backup")
		backup
		;;
	"restore")
		restore
		;;
	"help")
		echo "use backup or restore"
		;;
esac
