#! /bin/bash

MODEL_FILE="/sys/firmware/devicetree/base/model"

if [ ! -f "$MODEL_FILE" ]; then
    echo "ERROR: Cannot detect hardware model"
    exit 1
fi

MODEL=$(tr -d '\0' < "$MODEL_FILE")

case "$MODEL" in

    *"iW-RainboW-G34M-i.MX8MM-SODIMM-2GB"*)
        PLATFORM="imx8"
        ;;

    *"Raspberry Pi Compute Module 5 Rev 1.0"*)
        PLATFORM="rpi"
        ;;

    *)
        echo "ERROR: Unsupported platform"
        echo "Model: $MODEL"
        exit 1
        ;;

esac

echo "Model  : $MODEL"
echo "Platform: $PLATFORM"

#Result_Array
#ResultName[1]="SD Card Test";
ResultName[1]="Rotary Switch Test";
ResultName[2]="RTC Test";
ResultName[3]="ComPort(RS-485, RS-232) Test";
ResultName[4]="Ethernet Test";
ResultName[5]="LED Test";
ResultName[6]="Buzzer Test";

case "$PLATFORM" in
	imx8)
		# 檢查 SSD 裝置是否存在
		SSD_DEVICE="/dev/nvme0n1"
		if [ -e "$SSD_DEVICE" ]; then
    		ResultName[7]="SSD Test"
    		HasSSD=1
		else
	    	HasSSD=0
		fi
		;;
	rpi)
		# 檢查 USB 裝置是否存在
		USB_DEVICE="/dev/sda1"
		if [ -e "$USB_DEVICE" ]; then
    		ResultName[7]="USB Test"
    		HasUSB=1
		else
	    	HasUSB=0
		fi
		;;
esac

ResultOKLOG()
{
	ECHO_GREEN "[Result Test OK.]" >> /icpdas/tmp/BRKSeriesQC.log;
}
ResultErrorLOG()
{
	ECHO_YELLOW "[Result Test Error.]" >> /icpdas/tmp/BRKSeriesQC.log;
}

ResultOK()
{
	ECHO_GREEN "[Result Test OK.]";
}
ResultError()
{
	ECHO_YELLOW "[Result Test Error.]";
}
ECHO_RED()
{
	printf "\E[0;31;40m";
	echo "$1";
	printf "\E[0m";
}
ECHO_GREEN()
{
	printf "\E[0;32;40m";
	echo "$1";
	printf "\E[0m";
}
ECHO_YELLOW()
{
	printf "\E[0;33;40m";
	echo "$1";
	printf "\E[0m";
}
# 檢查 systemd 服務是否存在（不看有沒有啟動，只看有沒有裝這個服務）
ServiceExists()
{
	systemctl list-unit-files --type=service 2>/dev/null | grep -q "^$1\.service"
}
# 把點分十進位遮罩 (例如 255.255.0.0) 轉成 ip addr 需要的 CIDR 前綴長度 (例如 16)
NetmaskToCidr()
{
	local mask="$1"
	local cidr=0
	local IFS=.
	for octet in $mask; do
		case "$octet" in
			255) cidr=$((cidr + 8)) ;;
			254) cidr=$((cidr + 7)) ;;
			252) cidr=$((cidr + 6)) ;;
			248) cidr=$((cidr + 5)) ;;
			240) cidr=$((cidr + 4)) ;;
			224) cidr=$((cidr + 3)) ;;
			192) cidr=$((cidr + 2)) ;;
			128) cidr=$((cidr + 1)) ;;
			0)   ;;
		esac
	done
	echo "$cidr"
}
# 用 ip addr / ip route 設定介面的靜態 IP/遮罩/閘道，取代舊的
# `ipv4set <interface> static <IP> <Mask> <Gateway>` 指令。
# 用法：SetStaticIPAddress <interface> <IP> <Mask> <Gateway>
SetStaticIPAddress()
{
	local interface="$1"
	local ip="$2"
	local mask="$3"
	local gateway="$4"
	local cidr
	cidr=$(NetmaskToCidr "$mask")

	# 先清掉該介面既有的 IP 設定，避免舊位址殘留（ip addr add 是新增，不會自動取代舊的）
	ip addr flush dev "$interface"

	# 設定新的 IP / 遮罩
	ip addr add "${ip}/${cidr}" dev "$interface"

	# 確保介面是 up 的狀態
	ip link set "$interface" up

	# gateway 不屬於 ip addr 的管轄範圍，預設閘道用 ip route 設定。
	# "0.0.0.0" 沿用舊 ipv4set 的慣例，代表「這張網卡刻意不具備對外連網能力」
	# （0.0.0.0 本身也不是合法的 next-hop，直接下去會出錯）。
	# 不只是不新增而已，還要主動清掉可能殘留的預設路由（例如這張介面稍早
	# 還在 DHCP 模式時，已經從 DHCP server 拿到一條預設路由），確保真的
	# 連不到外網，不會因為「舊路由沒清」而讓限制形同虛設。
	if [ "$gateway" != "0.0.0.0" ]; then
		ip route replace default via "$gateway" dev "$interface"
	else
		ip route del default dev "$interface" 2>/dev/null || true
	fi
}
# 讓介面走 DHCP，取代舊的 `ipv4set <interface> dhcp` 指令。
# ip addr 本身不懂 DHCP 協定，實際的 DHCP 動作要交給對應平台裝的 DHCP
# client 執行：imx8 平台只有 dhclient，rpi 平台只有 dhcpcd。
# 用法：SetDhcpIPAddress <interface>
SetDhcpIPAddress()
{
	local interface="$1"

	# 換成 DHCP 前先清掉舊的靜態位址，避免殘留干擾 DHCP client 判斷
	ip addr flush dev "$interface"
	ip link set "$interface" up

	case "$PLATFORM" in
		imx8)
			# -r 先釋放舊 lease，避免重複執行時同一介面疊出多個 dhclient process
			dhclient -r "$interface" 2>/dev/null
			dhclient "$interface"
			;;
		rpi)
			# -k 先停掉該介面既有的 dhcpcd，避免重複執行時衝突
			dhcpcd -k "$interface" 2>/dev/null
			dhcpcd "$interface"
			;;
	esac
}
# 1 SD
TestSDCard()
{
	echo "";
	echo "################ ($1)MicroSD Card ################";
	SD_Path=`fdisk -l | grep '/dev/mmcblk0p1'`;
	if [ "$SD_Path" != "" ] ; then
	{
		ResultOK;
		Result_Array[$1]="1";
	}
	else
	{
		ECHO_YELLOW "Error, Please confirm whether to insert the SD Card, Or Request Relevant personnel Support, Thanks.";
		Result_Array[$1]="2";
		ResultError;
	}
	fi
}
# 2 RSW
TestRotarySwitch()
{
	Reg=0;
	Ans=0;
	echo "";
	echo "################ ($1)Rotary Switch ################";
	Start=`rsw`;
	while true
	do
		Command=`rsw`;
		if [ "$Start" != 0 ] ; then
		{
			ECHO_YELLOW "Error, Please, Check you Rotary Switch Start at '0', Thanks.";
			Result_Array[$1]="2";
			ResultError;
			break;
		}
		fi
		#echo "rsw: $Command";
		#echo "Reg: $Reg";
		#echo "Ans: $Ans";
		#echo $Command;
		
		if [ "$Ans" == 11 ] ; then
		{
			ResultOK;
			Result_Array[$1]="1";
			break;
			
		}
		fi
		if [ "$Reg" == 10 ] ; then
		{
			Reg=0;
		}
		fi
		
		if [ "$Command" == "$Reg" ] ; then
		{
			echo "$Command";
			Ans=`expr $Ans + 1`;
			Reg=`expr $Reg + 1`;
		}
		fi
		sleep 0.01;
	done
}
# 3 RTC
TestRTC()
{
	echo "################ ($1)RTC ################";
	echo "Please just a moment, RTC time setting ... ";
	Ping=`ping -q -c 1 -W 1 180.76.76.76 | grep " 0% packet loss"`;
    echo Asia/Taipei > /etc/timezone;
	dpkg-reconfigure --frontend noninteractive tzdata;
	hwclock -w;
	sync;
	ResultOK;
	#ECHO_GREEN "Result Test OK.";
	Result_Array[$1]="1";
}
# 4 ComPort Test
TestComPort()
{
	echo "################ ($1)COM1~COM3 Test ################";
	ComPort;
	echo "Key '1' or '2' is OK or Error.";
	read -p "Please Choose: " Choose;
	Result_Array[$1]="$Choose";
	if [ "$Choose" == "1" ] ; then
	{
		ResultOK;
	}
	else
	{
		ResultError;
	}
	fi
}
# 5 Ethernet
TestEthernet()
{
	echo "################ ($1)Auto Ethernet Test ################";
	eth0_Result="0";
	eth1_Result="0";

	SetDhcpIPAddress eth0;
	sleep 1;
	SetDhcpIPAddress eth1;
	sleep 1;

	SetStaticIPAddress eth0 192.168.255.20 255.255.0.0 192.168.1.1;
    sleep 2;

	# Ping=`ping -I eth0 -q -c 1 -W 1 8.8.8.8 | grep " 0% packet loss"`;
	Ping=`ping -I eth0 -q -c 1 -W 1 192.168.255.2 | grep " 0% packet loss"`;
    if [ "$Ping" != "" ] ; then
    {
    	ECHO_GREEN "eth0 test successed"
    	eth0_Result="1";
	}
	else
	{
		ECHO_YELLOW "Error, Please, Check your eth0, Or Request Relevant personnel Support, Thanks."
	}
    fi

    SetStaticIPAddress eth1 10.0.7.10 255.255.0.0 0.0.0.0;
    sleep 2;

    #Ping=`ping -I eth1 -q -c 1 -W 1 192.168.255.2 | grep " 0% packet loss"`;
    Ping=`ping -I eth1 -q -c 1 -W 1 10.0.7.168 | grep " 0% packet loss"`;
    if [ "$Ping" != "" ] ; then
    {
    	ECHO_GREEN "eth1 test successed"
        eth1_Result="1";
    }
	else
	{
		ECHO_YELLOW "Error, Please, Check your eth1, Or Request Relevant personnel Support, Thanks."
	}
    fi

    if [ $eth0_Result -eq "1" ] && [ $eth1_Result -eq "1" ] ; then
    {
    	ResultOK;
		Result_Array[$1]="1";
		
		SetStaticIPAddress eth0 192.168.255.1 255.255.0.0 192.168.1.1;
		SetStaticIPAddress eth1 10.0.7.1 255.255.0.0 0.0.0.0;

		JSON_FILE="/app/Web/File/brk.json"
		CONF_FILE="/etc/emqx/emqx.conf"
		INTERFACE="eth1"

		echo "--- [1/3] Getting IP address of $INTERFACE ---"
		# Get IPv4 address of eth1 and filter out subnet mask (/24 etc.)
		# HOST_IP=$(ip -4 addr show "$INTERFACE" 2>/dev/null | awk '/inet / {print $2}' | cut -d/ -f1)

		HOST_IP=$(/app/run/detect_ip.sh)

		if [ -z "$HOST_IP" ]; then
			echo "Error: Cannot get inet IP"
			exit 1
		fi

		if [ -z "$HOST_IP" ]; then
		    echo "Error: Failed to get IP address of $INTERFACE. Please check if the interface exists and is up."
		    exit 1
		fi
		echo "Successfully got IP: $HOST_IP"

		echo "--- [2/3] Reading NodeName from $JSON_FILE ---"
		if [ ! -f "$JSON_FILE" ]; then
		    echo "Error: JSON file $JSON_FILE not found."
		    exit 1
		fi

		# Native command fallback (assuming standard JSON format with line breaks)
		NODE_NAME=$(cat $JSON_FILE | tr -d '\n\r ' | grep -o '"NodeName":"[^"]*"' | head -n 1 | cut -d'"' -f4)

		if [ -z "$NODE_NAME" ]; then
		    echo "Error: Failed to find NodeName under LocalBrokerSetting in $JSON_FILE."
		    exit 1
		fi

		echo "Successfully got NodeName: $NODE_NAME"
		NEW_NODE_NAME="${NODE_NAME}@${HOST_IP}"
		echo "New node name to be set: $NEW_NODE_NAME"

		echo "--- [3/3] Updating EMQX configuration file ---"
		if [ ! -f "$CONF_FILE" ]; then
		    echo "Error: EMQX configuration file $CONF_FILE not found."
		    echo "Please check if the file path is correct (usually etc/emqx.conf)."
		    exit 1
		fi

		sed -i "s/^node.name =.*/node.name = ${NEW_NODE_NAME}/" "$CONF_FILE"

		echo "Configuration file updated successfully!"

		systemctl restart Web.service;
    }
	else
	{
		ResultError;
		Result_Array[$1]="2";	
	}
	fi
}

# 6 Led
OnOffLed()
{
	/usr/sbin/iTalk/led $1 -o1;
	sleep 2;
	/usr/sbin/iTalk/led $1 -o0;
}

TestLed()
{

	echo "################ ($1)LED Test ################";
	while [ $Choose != 5 ]
	do
	{
		echo "Test ";
		ECHO_GREEN "   1. Left Num1 Led Test.";
		ECHO_GREEN "   2. Left Num2 Led Test.";
		ECHO_GREEN "   3. Left Num3 Led Test.";
		ECHO_GREEN "   4. quit.";
		Choose=0;
		read -p "Please Choose: " Choose;
		if [ "$Choose" == "1" ] ; then
		{
			OnOffLed -l1;
		}
		elif [ "$Choose" == "2" ] ; then
		{
			OnOffLed -l2;
		}
		elif [ "$Choose" == "3" ] ; then
		{
			OnOffLed -l3;
		}
		elif [ "$Choose" == "4" ] ; then
		{
			break;
		}
		fi
	}
	done
	echo "Key '1' or '2' is OK or Error.";
	read -p "Please Choose: " Choose;
	Result_Array[$1]="$Choose";
	if [ "$Choose" == "1" ] ; then
	{
		ResultOK;
	}
	else
	{
		ResultError;
	}
	fi
}
# 7 Buzzer
TestBuzzer()
{
	echo "################ ($1)Buzzer Test ################";
	beep;
	echo "Key '1' or '2' is OK or Error.";
	read -p "Please Choose: " Choose;
	Result_Array[$1]="$Choose";
	if [ "$Choose" == "1" ] ; then
	{
		ResultOK;
	}
	else
	{
		ResultError;
	}
	fi
}
# 8 SSD
TestSSD()
{
	echo "################ ($1)SSD Test ###############";
	echo "Please wait, SSD test is in progress..."
	bash /usr/local/bin/SSD_QC.sh;
	if [ $? -eq 0 ]; then
		if ServiceExists influxdb; then
			INFLUXDB_RESULT=$(/app/run/check_influxdb_version.sh)
			if [ "$INFLUXDB_RESULT" == "V1" ]; then
				echo "Copying InfluxDB V1 configuration files..."
				tar -C /mnt/SSD -xf /icpdas/database/influxdb.tgz
			elif [ "$INFLUXDB_RESULT" == "V2" ]; then
				echo "Copying InfluxDB V2 configuration files..."
				tar -C /mnt/SSD -xf /icpdas/database/influxdbV2.tgz
				cp -a /icpdas/database/config.toml /etc/influxdb
			fi

			systemctl enable influxdb
			systemctl start influxdb

			sleep 2

			/app/run/initial_influxdb_token.sh
		else
			echo "influxdb service not found, skip InfluxDB initialization."
		fi

		## MariaDB
		if ServiceExists mariadb; then
			tar -C /mnt/SSD -xf /icpdas/database/mysql.tgz

			# 修改 MariaDB config
			config_file="/etc/mysql/mariadb.conf.d/50-server.cnf"
			backup_file="/etc/mysql/mariadb.conf.d/50-server.cnf.bak"
			new_path="/mnt/SSD/mysql"

			if [ ! -f "$config_file" ]; then
	    		echo "Configuration file not found: $config_file"
			fi

			cp "$config_file" "$backup_file"

			# 修改 datadir 路徑
			sed -i "s|^\s*datadir\s*=.*|datadir = $new_path|" "$config_file"
			# 尋找 bind-address 並替換為 0.0.0.0
			sed -i 's/^[[:space:]]*bind-address[[:space:]]*=.*/bind-address            = 0.0.0.0/' "$config_file"

			# 設定 MariaDB root密碼及預設 user
			systemctl start mariadb

			sleep 2

			ROOT_PW="12345"
			NEW_USER="user1"
			NEW_PW="1234"

			echo "Setting MariaDB root password..."
			mariadb -u root -e "ALTER USER 'root'@'localhost' IDENTIFIED BY '${ROOT_PW}';"

			echo "Removing MariaDB anonymous accounts..."
			mariadb -u root -p"${ROOT_PW}" -e "DELETE FROM mysql.user WHERE User='';"

			echo "Disabling root remote login..."
			mariadb -u root -p"${ROOT_PW}" -e "DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');"

			echo "Removing test database..."
			mariadb -u root -p"${ROOT_PW}" -e "DROP DATABASE IF EXISTS test; DELETE FROM mysql.db WHERE Db='test' OR Db='test\\\\_%';"

			mariadb -u root -p"${ROOT_PW}" -e "FLUSH PRIVILEGES;"

			echo "Creating MariaDB user: ${NEW_USER}..."
			mariadb -u root -p"${ROOT_PW}" -e "CREATE USER IF NOT EXISTS '${NEW_USER}'@'%' IDENTIFIED BY '${NEW_PW}';"
			mariadb -u root -p"${ROOT_PW}" -e "GRANT ALL PRIVILEGES ON *.* TO '${NEW_USER}'@'%';"

			mariadb -u root -p"${ROOT_PW}" -e "FLUSH PRIVILEGES;"

			systemctl stop mariadb
			echo "MariaDB configuration completed!"
		else
			echo "mariadb service not found, skip MariaDB initialization."
		fi

		## MongoDB
		if ServiceExists mongod; then
			CONF_FILE="/etc/mongod.conf"
			NEW_DB_PATH="/mnt/SSD/mongodb"

			# 修改 dbPath
			sed -i "s|dbPath: /var.*|dbPath: $NEW_DB_PATH|" "$CONF_FILE"

			# 修改 bindIp
			sed -i "s/bindIp: .*/bindIp: 0.0.0.0/" "$CONF_FILE"

			# 建立 MongoDB目錄
			rm -rf /mnt/SSD/mongodb
			mkdir -p /mnt/SSD/mongodb
			chmod 755 /mnt/SSD/mongodb
			chown -R mongodb:mongodb "$NEW_DB_PATH"
			chown -R mongodb:mongodb /var/log/mongodb/mongod.log

			echo "MongoDB configuration completed!"

			systemctl start mongod

			sleep 2

			# MongoDB 帳號建立與授權設定
			DMIN_USER="admin"
			ADMIN_PWD="AdminPassword123"
			DATA_USER="user1"
			DATA_PWD="1234"
			CONF_FILE="/etc/mongod.conf"

			echo "--- [1/3] Checking MongoDB Service ---"

			if ! systemctl is-active --quiet mongod; then
				echo "Error: MongoDB service is not running."
				return 1
			fi

			echo "--- [2/3] Creating Database Accounts ---"
			# 建立第一個管理員 (無需驗證)
			mongo admin --eval "db.createUser({user: '$ADMIN_USER', pwd: '$ADMIN_PWD', roles: [{role: 'userAdminAnyDatabase', db: 'admin'}, 'readWriteAnyDatabase']})"

			# 建立數據維護員 (需透過 admin 驗證)
			mongo admin -u "$ADMIN_USER" -p "$ADMIN_PWD" --authenticationDatabase admin --eval "db.createUser({user: '$DATA_USER', pwd: '$DATA_PWD', roles: [{role: 'readWriteAnyDatabase', db: 'admin'}]})"

			echo "--- [3/3] Enabling Authentication ---"
			if [ -f "$CONF_FILE" ]; then
				cp "$CONF_FILE" "${CONF_FILE}.bak"
				sed -i '/^security:/d' "$CONF_FILE"
				sed -i '/authorization:/d' "$CONF_FILE"
				echo -e "security:\n  authorization: enabled" >> "$CONF_FILE"

				systemctl stop mongod
				echo "MongoDB authentication has been enabled successfully."
			else
				echo "Error: Configuration file $CONF_FILE not found."
			fi
		else
			echo "mongod service not found, skip MongoDB initialization."
		fi

		Result_Array[$1]="1";
    	ResultOK;
	else
		Result_Array[$1]="0";
    	ResultError;
	fi
}
# 8 USB
TestUSB()
{
	echo "################ ($1)USB Test ###############";
	echo "Please wait, USB test is in progress..."
	bash /usr/local/bin/USB_QC.sh;
	if [ $? -eq 0 ]; then
		# Detect USB mount path
		#USB_PATH=$(findmnt -n -o TARGET /dev/sda1)
		USB_PATH="/mnt/USB"

		if [ -z "$USB_PATH" ]; then
			echo "Error: /dev/sda1 is not mounted."
			exit 1
		fi

		echo "USB device detected:"
		echo "  Device : /dev/sda1"
		echo "  Path   : $USB_PATH"

		if ServiceExists influxdb; then
			INFLUXDB_RESULT=$(/app/run/check_influxdb_version.sh)

			if [ "$INFLUXDB_RESULT" == "V1" ]; then

				echo "Copying InfluxDB V1 configuration files..."

				tar -C "$USB_PATH" -xf /icpdas/database/influxdb.tgz

			elif [ "$INFLUXDB_RESULT" == "V2" ]; then

				echo "Copying InfluxDB V2 configuration files..."

				tar -C "$USB_PATH" -xf /icpdas/database/influxdbV2.tgz

				cp -a /icpdas/database/config.toml /etc/influxdb
				sed -i "s|/mnt/SSD/|${USB_PATH}/|g" /etc/influxdb/config.toml
			fi

			systemctl enable influxdb
			systemctl start influxdb

			sleep 2

			/app/run/initial_influxdb_token.sh
		else
			echo "influxdb service not found, skip InfluxDB initialization."
		fi

		# MariaDB
		if ServiceExists mariadb; then
			tar -C "$USB_PATH" -xf /icpdas/database/mysql.tgz

			config_file="/etc/mysql/mariadb.conf.d/50-server.cnf"
			backup_file="/etc/mysql/mariadb.conf.d/50-server.cnf.bak"

			new_path="$USB_PATH/mysql"

			if [ ! -f "$config_file" ]; then
				echo "Configuration file not found: $config_file"
				exit 1
			fi

			cp "$config_file" "$backup_file"

			# 修改 MariaDB datadir 路徑
			sed -i "s|^[[:space:]]*datadir[[:space:]]*=.*|datadir = $new_path|" "$config_file"

			# 修改 bind-address
			sed -i 's/^[[:space:]]*bind-address[[:space:]]*=.*/bind-address            = 0.0.0.0/' "$config_file"

			# 設定 MariaDB root 密碼及預設 user
			systemctl start mariadb

			sleep 2

			ROOT_PW="12345"
			NEW_USER="user1"
			NEW_PW="1234"

			echo "Setting MariaDB root password..."

			mariadb -u root -e \
					"ALTER USER 'root'@'localhost' IDENTIFIED BY '${ROOT_PW}';"

			echo "Removing MariaDB anonymous accounts..."

			mariadb -u root -p"${ROOT_PW}" -e \
					"DELETE FROM mysql.user WHERE User='';"

			echo "Disabling root remote login..."

			mariadb -u root -p"${ROOT_PW}" -e \
					"DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');"

			echo "Removing test database..."

			mariadb -u root -p"${ROOT_PW}" -e \
					"DROP DATABASE IF EXISTS test; DELETE FROM mysql.db WHERE Db='test' OR Db='test\\\\_%';"

			mariadb -u root -p"${ROOT_PW}" -e \
					"FLUSH PRIVILEGES;"

			echo "Creating MariaDB user: ${NEW_USER}..."

			mariadb -u root -p"${ROOT_PW}" -e \
					"CREATE USER IF NOT EXISTS '${NEW_USER}'@'%' IDENTIFIED BY '${NEW_PW}';"

			mariadb -u root -p"${ROOT_PW}" -e \
					"GRANT ALL PRIVILEGES ON *.* TO '${NEW_USER}'@'%';"

			mariadb -u root -p"${ROOT_PW}" -e \
					"FLUSH PRIVILEGES;"

			systemctl stop mariadb

			echo "MariaDB configuration completed!"
		else
			echo "mariadb service not found, skip MariaDB initialization."
		fi

		# MongoDB
		## CONF_FILE="/etc/mongod.conf"
		## NEW_DB_PATH="$USB_PATH/mongodb"

		# 修改 dbPath
		## sed -i "s|dbPath: /var.*|dbPath: $NEW_DB_PATH|" "$CONF_FILE"

		# 修改 bindIp
		## sed -i "s/bindIp: .*/bindIp: 0.0.0.0/" "$CONF_FILE"

		# 建立 MongoDB 目錄
		## rm -rf "$NEW_DB_PATH"

		## mkdir -p "$NEW_DB_PATH"

		## chmod 755 "$NEW_DB_PATH"

		## chown -R mongodb:mongodb "$NEW_DB_PATH"

		## chown -R mongodb:mongodb /var/log/mongodb/mongod.log

		## echo "MongoDB configuration completed!"

		## systemctl start mongod

		## sleep 2

		# MongoDB Account
		## ADMIN_USER="admin"
		## ADMIN_PWD="AdminPassword123"

		## DATA_USER="user1"
		## DATA_PWD="1234"

		## CONF_FILE="/etc/mongod.conf"

		## echo "--- [1/3] Checking MongoDB Service ---"

		## if ! systemctl is-active --quiet mongod; then
		## 		echo "Error: MongoDB service is not running."
		## 		exit 1
		## fi

		## echo "--- [2/3] Creating Database Accounts ---"

		# 建立第一個管理員
		## mongo admin --eval \
		## 		"db.createUser({user: '$ADMIN_USER', pwd: '$ADMIN_PWD', roles: [{role: 'userAdminAnyDatabase', db: 'admin'}, 'readWriteAnyDatabase']})"

		# 建立數據維護員
		## mongo admin \
		## 		-u "$ADMIN_USER" \
		## 		-p "$ADMIN_PWD" \
		## 		--authenticationDatabase admin \
		## 		--eval \
		## 		"db.createUser({user: '$DATA_USER', pwd: '$DATA_PWD', roles: [{role: 'readWriteAnyDatabase', db: 'admin'}]})"

		## echo "--- [3/3] Enabling Authentication ---"

		## if [ -f "$CONF_FILE" ]; then

		## 		cp "$CONF_FILE" "${CONF_FILE}.bak"

		## 		sed -i '/^security:/d' "$CONF_FILE"
		## 		sed -i '/authorization:/d' "$CONF_FILE"

		## 		echo -e "security:\n  authorization: enabled" >> "$CONF_FILE"

		## 		systemctl stop mongod

		## 		echo "MongoDB authentication has been enabled successfully."

		## else
		## 		echo "Error: Configuration file $CONF_FILE not found."
		## fi

		Result_Array[$1]="1";
    	ResultOK;
	else
		Result_Array[$1]="0";
    	ResultError;
	fi
}
TestResultList()
{
	echo  "================ Test Result List ===============";
	Date=`date +%Y/%m/%d-%H:%M:%S`;
	echo -e -n "Date & Now Time: ";
	ECHO_YELLOW $Date;
	echo "";

	allTestsPassed=true;

	length=${#ResultName[@]}

	#for i in {1..7};
	for (( i=1; i<=length; i++ )); do
	{
		echo -e -n "$i. ${ResultName[i]} is ";
		if [ "${Result_Array[i]}" == "1" ]; then
		{
			ResultOK;
		}
		else
		{
			ResultError;
			allTestsPassed=false;
		}
		fi
	}
	done

	if $allTestsPassed ; then
	{
		eep -w  128 $(date +%Y/%m/%d-%H:%M:%S)" QC success" -s;
	}
	else
	{
		eep -w  128 $(date +%Y/%m/%d-%H:%M:%S)" QC fail" -s;
	}
	fi
	
	echo "Thank you Use BRKSeries QC Test.";
}
TestResultListLog()
{
	echo  "================ Test Result List ===============" >> /icpdas/tmp/BRKSeriesQC.log;
	Date=`date +%Y/%m/%d-%H:%M:%S`;
	echo -e -n "Date & Now Time: " >> /icpdas/tmp/BRKSeriesQC.log;
	ECHO_YELLOW $Date >> /icpdas/tmp/BRKSeriesQC.log;
	echo "" >> /icpdas/tmp/BRKSeriesQC.log;
	
	case "$PLATFORM" in
		imx8)
			max=$([ "$HasSSD" == "1" ] && echo 7 || echo 6)
			;;
		rpi)
			max=$([ "$HasUSB" == "1" ] && echo 7 || echo 6)
			;;
		*)
			max=7
			;;
	esac
	for ((i=1; i<=max; i++)); do
		echo -e -n "$i. ${ResultName[i]} is " >> /icpdas/tmp/BRKSeriesQC.log;
		if [ "${Result_Array[i]}" == "1" ]; then
		{
			ResultOKLOG;
		}
		else
		{
			ResultErrorLOG;
		}
		fi
	done
	#for i in {1..7};
	#do
	#{
	#	echo -e -n "$i. ${ResultName[i]} is " >> /icpdas/tmp/BRKSeriesQC.log;
	#	if [ "${Result_Array[i]}" == "1" ]; then
	#	{
	#		ResultOKLOG;
	#	}
	#	else
	#	{
	#		ResultErrorLOG;
	#	}
	#	fi
	#}
	#done
	echo "Thank you Use BRKSeries QC Test." >> /icpdas/tmp/BRKSeriesQC.log;
}


Auto_Function()
{
	echo "Test ";
	printf "\E[0;32;40m";
	#echo "   1. SD Card Test.";
	echo "   1. Rotary Switch Test.";
	echo "   2. RTC Test.";
	echo "   3. ComPort(RS-485, RS-232) Test.";
	echo "   4. Ethernet Test.";
	echo "   5. LED Test.";
	echo "   6. Buzzer Test";
	case "$PLATFORM" in
		imx8)
			if [ "$HasSSD" == 1 ]; then
			{
				echo "   7. ${ResultName[7]}.";
			}
			fi
			;;
		rpi)
			if [ "$HasUSB" == 1 ]; then
			{
				echo "   7. ${ResultName[7]}.";
			}
			fi
			;;
	esac
	printf "\E[0m";
}
Single_Function()
{
	echo "Test ";
	printf "\E[0;32;40m";
	#echo "   1. SD Card Test.";
	echo "   1. Rotary Switch Test.";
	echo "   2. RTC Test.";
	echo "   3. ComPort(RS-485, RS-232) Test.";
	echo "   4. Ethernet Test.";
	echo "   5. LED Test.";
	echo "   6. Buzzer Test";
	case "$PLATFORM" in
		imx8)
			if [ "$HasSSD" == 1 ]; then
			{
				echo "   7. ${ResultName[7]}.";
			}
			fi
			;;
		rpi)
			if [ "$HasUSB" == 1 ]; then
			{
				echo "   7. ${ResultName[7]}.";
			}
			fi
			;;
	esac
	echo "   10. quit";
	printf "\E[0m";
	read -p "Please Choose: " Choose;
	#if [ "$Choose" == "1" ]; then
	#{
	#		TestSDCard 1;
	#}
	if [ "$Choose" == "1" ]; then
	{
		TestRotarySwitch 1;
	}
	elif [ "$Choose" == "2" ]; then
	{
		TestRTC 2;
	}
	elif [ "$Choose" == "3" ]; then
	{
		TestComPort 3;
	}
	elif [ "$Choose" == "4" ]; then
	{
		echo "4";
		TestEthernet 4;
	}
	elif [ "$Choose" == "5" ]; then
	{
		echo "5";
		TestLed 5;
	}
	elif [ "$Choose" == "6" ]; then
	{
		echo "6";
		TestBuzzer 6;
	}
	elif [ "$Choose" == "7" ]; then
	{
		case "$PLATFORM" in
			imx8)
				if [ "$HasSSD" == 1 ]; then
				{
					TestSSD 7
				}
				fi
				;;
			rpi)
				if [ "$HasUSB" == 1 ]; then
				{
					TestUSB 7
				}
				fi
				;;
			esac
	}
	elif [ "$Choose" == "10" ]; then
	{
		exit 0;
	}
	fi
}
#Model=`EEP_GetModelName`;
echo "Welcome To ICPDAS UASeries QC Test.";
#echo -e -n "Model is ";
#printf "\E[0;32;40m"; echo "$Model"; printf "\E[0m";
echo  "==============================================";
echo "";
echo "Please Key '1' or '2' is Auto Test or Single Test.";
echo "  1. Auto Test.";
echo "  2. Single Test.";
read -p "Please Choose: " Choose;
echo -e -n "You Choose is $Choose ";
if [ "$Choose" == "1" ]; then
{
	echo "Auto Test Start."
	Auto_Function;
	sleep 2;
	#TestSDCard 1;
	TestRotarySwitch 1;
	TestRTC 2;
	TestComPort 3;
	TestEthernet 4;
	TestLed 5;
	TestBuzzer 6;
	case "$PLATFORM" in
		imx8)
			if [ "$HasSSD" == 1 ]; then
			{
				TestSSD 7;
			}
			fi
			;;
		rpi)
			if [ "$HasUSB" == 1 ]; then
			{
				TestUSB 7;
			}
			fi
			;;
	esac
	
	echo "";echo "";
	TestResultList;
	TestResultListLog;
	mkdir /mnt/SD;mkdir /mnt/USB;mkdir /mnt/SSD;mkdir /mnt/Utility;
}
elif [ "$Choose" == "2" ]; then
{
	echo "Single Test Start."
	Single_Function;
}
fi
