#!/bin/sh

###############################################
#
# check the tos exists
#
###############################################

if [ -z $1 ]; then
	echo "Usage:`basename $0` [/dev/sd?2]"
	exit 1
fi

if [ ! -b $1 ]; then
	echo "Error: $1 is not block"
	exit 1
fi

tmpraid=/dev/md100
mntpath=/tmp/check
mdadm -A $tmpraid $1 --force
if [ $? -ne 0 ]; then
	echo "Error: it is not a raid block"
	exit 1
else
	mkdir -p $mntpath
	mount $tmpraid $mntpath
	if [ $? -ne 0 ]; then
		mdadm -S $tmpraid
		echo "Error: not found filesystem"
		exit 1
	else
		if [ -f $mntpath/sbin/init ]; then
			if [ ! -f /tmp/nginx.conf ]; then
				nginxconf=$mntpath/etc/nginx/nginx.conf
				port=$(sed -n '/\#\s*HTTP\s*server\b/,/\#\s*HTTP\s*server\b/{/[^#][ |  |   |    |\t]*\blisten\b/p}' "$nginxconf" | awk '{print $2}' | awk -F";" '{print $1}')
				echo "$port" > /tmp/nginx.conf
			fi
			umount $mntpath
			mdadm -S $tmpraid
			echo "Correct: exists tos system"
			exit 0
		else
			umount $mntpath
			mdadm -S $tmpraid
			echo "Error: not exists tos system"
			exit 1
		fi
	fi
fi
