#!/bin/sh

source /etc/tos/scripts/scripts

script_get_lock >/dev/null
[ $? -ne 0 ] && exit 1

compareVersion() {
	local input1="$1"
	local input2=$(cat /usr/lib/version)
	# compare first field
	local first1=$(echo $input1|cut -d"_" -f1)
	local first2=$(echo $input2|cut -d"_" -f1)
	if [ "$first1" != "$first2" ]; then
		return 1
	fi
	# compare second field
	local second1=$(echo $input1|cut -d"_" -f2)
	local second2=$(echo $input2|cut -d"_" -f2)
	if [ "$second1" != "$second2" ]; then
		return 1
	fi
	return 0
}

binFile=$1
tmpDir=/tmp/databack
jar=1
# backup the config
if [ "X${binFile}" = "X" ]; then
	rm -fr /etc/base/update
	mkdir -m 777 -p $tmpDir
	rm -fr $tmpDir/TNAS_*_config_backup.*
	configname="TNAS_$(hostname)_config_backup"
	cd /etc/
	tarFile=$tmpDir/${configname}.tar
	find . -type f | while read line; do
		# skip i18n multi languages
		echo $line | grep /i18n/ >/dev/null
		[ $? -eq 0 ] && continue
		# skip udev config
		echo $line | grep /udev/ >/dev/null
		[ $? -eq 0 ] && continue
		# skip pam.d config
		echo $line | grep /pam.d/ >/dev/null
		[ $? -eq 0 ] && continue
		# skip tos modules
		echo $line | grep /tos/modules/ >/dev/null
		[ $? -eq 0 ] && continue
		# skip ...
		echo $line | grep checksystem.db >/dev/null
		[ $? -eq 0 ] && continue
		# skip shell & binary
		file $line | grep executable >/dev/null
		[ $? -eq 0 ] && continue
		if [ ! -e $tarFile ]; then
			tar -cf $tarFile $line
		else
			tar -uf $tarFile $line
		fi
	done
  # 自启动配置
  services=("ntp")

  output_file="./service_autostart_status.txt"

  > "$output_file"

  # 遍历数组检查每个服务的开机启动状态
  for service in "${services[@]}"; do
      if systemctl is-enabled "$service" &>/dev/null; then
          echo "$service enabled" >> "$output_file"
      else
          echo "$service disabled" >> "$output_file"
      fi
  done
  tar -uf $tarFile "./service_autostart_status.txt"

	md5=$(md5sum $tarFile | awk '{print $1}')
	echo $md5 >$tmpDir/${configname}.bin
	dd if=/usr/lib/version of=$tmpDir/${configname}.bin bs=32 seek=1 >/dev/null 2>&1
	dd if=$tarFile of=$tmpDir/${configname}.bin bs=32 seek=2 >/dev/null 2>&1
	script_put_lock >/dev/null
	echo ${configname}.bin
	jar=0
else
	if [ -e "${binFile}" ]; then
		outFile=$(dirname $binFile)/config.tar
		md5value=$(dd if=$binFile bs=32 count=1 2>/dev/null|tr -d '\0')
		version=$(dd if=$binFile bs=32 skip=1 count=1 2>/dev/null|tr -d '\0')
		compareVersion "$version"
		if [ $? -eq 0 ]; then
			dd if=$binFile of=$outFile bs=32 skip=2 2>/dev/null
			md5new=$(md5sum $outFile | awk '{print $1}')
			if [ "${md5new}" = "${md5value}" ]; then
				tar -xf $outFile -C /etc/
        # 兼容旧版本，旧版本不存在软连接
        if [ $(tar -tvf $outFile | grep "^l" | wc -l) -gt 0 ]; then
          # 不再删除原有的软连接，以避免一些服务名变更或者使用新服务导致无法进入系统，虽然这可能让用户启动的服务变多
          # 解压自启动配置
          tar -xvf $outFile -C /etc/systemd/ --strip-components=2 etc/systemd/system/
        fi
        if [[ -f "/etc/service_autostart_status.txt" ]]; then
          while read -r line; do
            service=$(echo "$line" | awk '{print $1}')
            state=$(echo "$line" | awk '{print $2}')

            if [[ "$state" == "enabled" ]]; then
                systemctl enable "$service"
                echo "已启用 $service 的自启动"
            else
                systemctl disable "$service"
                echo "已禁用 $service 的自启动"
            fi
          done < "/etc/service_autostart_status.txt"
        fi
				jar=$?
				script_put_lock >/dev/null
        echo "ok!" >&2
			else
				echo "md5 value error" >&2
			fi
		else
			echo "invalid backup config" >&2
		fi
	fi
	script_put_lock >/dev/null
fi

exit $jar
