#!/usr/bin/env bash
#
# Copyright (C) 2022 Ing <https://github.com/wjz304>
# 
# This is free software, licensed under the MIT License.
# See /LICENSE for more information.
#

echo '### 本工具由 淘宝 Tank电玩[http://mi-d.cn] 维护 (v1.0.0) ###'

if [ "root" != "`whoami`" ]; then
  echo "请使用 root 用户执行该脚本"
  exit 1
fi

if [ -z "${1}" ]; then
    cat << EOF
Usage: 
   $0 <SN>
EOF
  exit 1
fi

SN=$1
BOOT=synoboot1

if [ ! -b "/dev/${BOOT}" ]; then 
  echo "未检测到引导分区, 清"
  exit 2
fi

echo 1 > /proc/sys/kernel/syno_install_flag

mkdir -p "/tmp/${BOOT}"  
mount "/dev/${BOOT}" "/tmp/${BOOT}" 

if [ ! -d "/tmp/${BOOT}" ]; then
  echo "引导分区挂载失败"
  exit 3
fi 

if [ -f "/tmp/${BOOT}/user-config.yml" ]; then
  echo "Cur is ARPL boot. "
  old=`grep '^sn:' /tmp/${BOOT}/user-config.yml | sed -r 's/sn:(.*)/\1/; s/[\" ]//g'`
  if [ -z "${old}" ]; then
    echo "未找到旧的SN"
    exit 4
  fi
  echo "[I] mod ${old} to ${SN}"
  sed -i "s/${old}/${SN}/g" /tmp/${BOOT}/user-config.yml
  
elif [ -f "/tmp/${BOOT}/boot/grub/grub.cfg" ]; then
  echo "Cur is Redpill boot. "
  olds=(`grep 'sn=' /tmp/${BOOT}/boot/grub/grub.cfg | sed -r 's/.*sn=([a-zA-Z0-9]{1,20})\ .*/\1/'`)
  if [ ${#olds[@]} -eq 0 ]; then
    echo "未找到旧的SN"
    exit 4
  fi
  for old in ${olds[@]}
  do
    echo "[I] mod ${old} to ${SN}"
    sed -i "s/${old}/${SN}/g" /tmp/${BOOT}/boot/grub/grub.cfg
  done
fi

umount "/tmp/${BOOT}"
echo "修改完成, 请重启系统并查看!"
echo "[I] 此脚本由 淘宝 Tank电玩[http://mi-d.cn] 提供, 感谢您的支持."
exit 0