
# 定义颜色变量
BLACK='\033[0;30m'
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
WHITE='\033[0;37m'
NC='\033[0m'

cpu_arch="amd64"
if [ $(uname -p) = "aarch64" ];then
  cpu_arch="arm64"
fi

############################################################
# log output
log_info(){
    content="[INFO] $(date '+%Y-%m-%d %H:%M:%S') $@"
    echo -e "${GREEN} ==> ${content} $NC"
}

log_warn(){
    content="[WARN] $(date '+%Y-%m-%d %H:%M:%S') $@"
    echo -e "${YELLOW} ==> ${content} $NC"
}

log_error(){
    content="[ERROR] $(date '+%Y-%m-%d %H:%M:%S') $@"
    echo -e "${RED} ==> ${content} $NC"
    exit 1
}


create_sed_file(){
  # 特殊资源,github 直接替换成 gitea，但是对于 raw 的资源 URL 和 gitea 不完全匹配，目前通过直接替换file的方式
  echo "s|//github.com/|//gitea.cncfstack.com/|g" > domain.sed
  echo "s|//raw.githubusercontent.com/|//cdn.cncfstack.com/raw.githubusercontent.com/|g" >> domain.sed

  # 常用资源
  echo "s|//code.jquery.com/|//cdn.cncfstack.com/code.jquery.com/|g" >> domain.sed
  echo "s|//unpkg.com/|//cdn.cncfstack.com/unpkg.com/|g" >> domain.sed
  echo "s|//stackpath.bootstrapcdn.com/|//cdn.cncfstack.com/stackpath.bootstrapcdn.com/|g" >> domain.sed
  echo "s|//cdn.jsdelivr.net/|//cdn.cncfstack.com/cdn.jsdelivr.net/|g" >> domain.sed
  echo "s|//maxcdn.bootstrapcdn.com/|//cdn.cncfstack.com/maxcdn.bootstrapcdn.com/|g" >> domain.sed
  echo "s|//cdnjs.cloudflare.com/|//cdn.cncfstack.com/cdnjs.cloudflare.com/|g" >> domain.sed
  echo "s|//cdn-images.mailchimp.com/|//cdn.cncfstack.com/cdn-images.mailchimp.com/|g" >> domain.sed
  echo "s|//buttons.github.io/|//cdn.cncfstack.com/buttons.github.io/|g" >> domain.sed
  echo "s|//fonts.gstatic.com/|//cdn.cncfstack.com/fonts.gstatic.com/|g" >> domain.sed
  echo "s|//img.youtube.com/|//cdn.cncfstack.com/img.youtube.com/|g"  >> domain.sed
  echo "s|//www.gstatic.com/|//cdn.cncfstack.com/www.gstatic.com/|g"  >> domain.sed
  
  # 肯存在导致异常的资源，google字体不是静态的资源，需要特殊处理
  echo "s|//fonts.googleapis.com/|//cdn.cncfstack.com/fonts.googleapis.com/|g" >> domain.sed
  echo "s|//www.google-analytics.com/|//cdn.cncfstack.com/www.google-analytics.com/|g" >> domain.sed
  echo "s|//www.googletagmanager.com/|//cdn.cncfstack.com/www.googletagmanager.com/|g" >> domain.sed
  echo "s|//use.fontawesome.com/|//cdn.cncfstack.com/use.fontawesome.com/|g" >> domain.sed
  echo "s|//ajax.googleapis.com/|//cdn.cncfstack.com/ajax.googleapis.com/|g" >> domain.sed
  
  # 其他
  echo "s|//pbs.twimg.com/|//cdn.cncfstack.com/pbs.twimg.com/|g"  >> domain.sed
  echo "s|//assets.adobedtm.com/|//cdn.cncfstack.com/assets.adobedtm.com/|g"  >> domain.sed
  echo "s|//cdn-images-1.medium.com/|//cdn.cncfstack.com/cdn-images-1.medium.com/|g" >> domain.sed
  echo "s|//js.hs-scripts.com/|//cdn.cncfstack.com/js.hs-scripts.com/|g" >> domain.sed
  echo "s|//cdn.cr-relay.com/|//cdn.cncfstack.com/cdn.cr-relay.com/|g" >> domain.sed
  echo "s|//cm.g.doubleclick.net/|//cdn.cncfstack.com/cm.g.doubleclick.net/|g" >> domain.sed
  echo "s|//connect.facebook.net/|//cdn.cncfstack.com/connect.facebook.net/|g" >> domain.sed
  echo "s|//d.adroll.com/|//cdn.cncfstack.com/d.adroll.com/|g" >> domain.sed
  echo "s|//ddzuuyx7zj81k.cloudfront.net/|//cdn.cncfstack.com/ddzuuyx7zj81k.cloudfront.net/|g" >> domain.sed
  echo "s|//dss6ntp5q2r0o.cloudfront.net/|//cdn.cncfstack.com/dss6ntp5q2r0o.cloudfront.net/|g" >> domain.sed
  echo "s|//dsum-sec.casalemedia.com/|//cdn.cncfstack.com/dsum-sec.casalemedia.com/|g" >> domain.sed
  echo "s|//eb2.3lift.com/|//cdn.cncfstack.com/eb2.3lift.com/|g" >> domain.sed
  echo "s|//forms.hsforms.com/|//cdn.cncfstack.com/forms.hsforms.com/|g" >> domain.sed
  echo "s|//gips0.baidu.com/|//cdn.cncfstack.com/gips0.baidu.com/|g" >> domain.sed
  echo "s|//ib.adnxs.com/|//cdn.cncfstack.com/ib.adnxs.com/|g" >> domain.sed
  echo "s|//idsync.rlcdn.com/|//cdn.cncfstack.com/idsync.rlcdn.com/|g" >> domain.sed
  echo "s|//image2.pubmatic.com/|//cdn.cncfstack.com/image2.pubmatic.com/|g" >> domain.sed
  echo "s|//img.alicdn.com/|//cdn.cncfstack.com/img.alicdn.com/|g" >> domain.sed
  echo "s|//ipv4.d.adroll.com/|//cdn.cncfstack.com/ipv4.d.adroll.com/|g" >> domain.sed
  echo "s|//match.adsrvr.org/|//cdn.cncfstack.com/match.adsrvr.org/|g" >> domain.sed

  echo "s|//ml314.com/|//cdn.cncfstack.com/ml314.com/|g" >> domain.sed
  echo "s|//munchkin.marketo.net/|//cdn.cncfstack.com/munchkin.marketo.net/|g" >> domain.sed
  echo "s|//pixel.rubiconproject.com/|//cdn.cncfstack.com/pixel.rubiconproject.com/|g" >> domain.sed
  echo "s|//pixel.tapad.com/|//cdn.cncfstack.com/pixel.tapad.com/|g" >> domain.sed
  echo "s|//platform.twitter.com/|//cdn.cncfstack.com/platform.twitter.com/|g" >> domain.sed
  echo "s|//px.ads.linkedin.com/|//cdn.cncfstack.com/px.ads.linkedin.com/|g" >> domain.sed
  echo "s|//s.adroll.com/|//cdn.cncfstack.com/s.adroll.com/|g" >> domain.sed
  echo "s|//snap.licdn.com/|//cdn.cncfstack.com/snap.licdn.com/|g" >> domain.sed
  echo "s|//static.redhat.com/|//cdn.cncfstack.com/static.redhat.com/|g" >> domain.sed
  echo "s|//storage.googleapis.com/|//cdn.cncfstack.com/storage.googleapis.com/|g" >> domain.sed
  echo "s|//translate.google.com/|//cdn.cncfstack.com/translate.google.com/|g" >> domain.sed
  echo "s|//us-u.openx.net/|//cdn.cncfstack.com/us-u.openx.net/|g" >> domain.sed
  echo "s|//www.abetterinternet.org/|//cdn.cncfstack.com/www.abetterinternet.org/|g" >> domain.sed
  echo "s|//www.redhat.com/|//cdn.cncfstack.com/www.redhat.com/|g" >> domain.sed
  echo "s|//x.adroll.com/|//cdn.cncfstack.com/x.adroll.com/|g" >> domain.sed
  echo "s|//x.bidswitch.net/|//cdn.cncfstack.com/x.bidswitch.net/|g" >> domain.sed

  #docker docs special
  echo "s|//docs.docker.com/|//docker.website.cncfstack.com/|g" >> domain.sed
}

change_url_to_file(){
    
    path=$1
    create_sed_file

    log_info "domain.sed 文件内容条数"
    cat domain.sed | wc -l
  
    #find $path  -type f > /tmp/sed-file-list
     find  $path -type f -iname "*.txt" \
         -o -iname "*.js" \
         -o -iname "*.css" \
         -o -iname "*.html" \
         -o -iname "*.tpl"  > /tmp/sed-file-list

    log_info "sed-file-list 文件内容的行数，在替换中...."
    cat /tmp/sed-file-list | wc -l

    # 循环依次处理可能包含外部链接的文件，并进行替换
    for file in `cat /tmp/sed-file-list`
    do
        file -b $file |grep "text"
        if [ $? -ne 0 ];then
            continue
        fi

        # log_info "$file 文件被替换"
  
        #log_info "部分CSS引用时会添加完整性校验，修改了文件后不删除校验会导致浏览器拒绝处理"
        sed -i 's/integrity="[^"]*"//g' $file  1>/dev/null

        #log_info "jaeger 中通过脚本的方式生成脚本，需要单独处理"
        #,script.integrity="sha256-waClS2re9NUbXRsryKoof+F9qc1gjjIhc2eT7ZbIv94=",script.crossOrigin="anonymous"
        sed -i 's/\,script\.integrity="[^"]*"//g' $file  1>/dev/null
        # 迁移到项目内容
        #sed -i 's|docs.openclaw.ai|openclaw-docs.website.cncfstack.com|g' $file 1>/dev/null

        #log_info "Kubevir 中文档目录导航位置的体会"
        sed -i 's|//kubevirt.io/user-guide|/user-guide/|g' $file 1>/dev/null
        sudo sed -i -f domain.sed $file 1>/dev/null

        
    done
          
    log_info "文件替换完成 done"

}
# 将ads的脚本输出到文件中
# args1: file_path 输出的文件路径
echo_google_ads(){
    file_path=$1
    echo $file_path
    [[ -f $file_path ]] || log_error "echo_goolge_ads 的目标路径不存在"
  
    echo '
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1160147761715358" data-overlays="collapsed-bottom" crossorigin="anonymous"> </script>
<script>(adsbygoogle = window.adsbygoogle || []).push({});</script>
<style> body {padding-bottom: 0 !important;}</style>
    ' >>  $file_path    
}


add_head_assets_for_mkdocs(){
    umami_website_id=$1
    theme=$2
    theme_version=$3
    set -x
  
    overrides_dir="./overrides"
    # 如果 cust没有配置，需要添加，否则 overrides 不生效
    # custom_dir: docs/mkdocs/overrides
   
    for mkdocs_config in "mkdocs.yml" "mkdocs.yaml"
    do
        if [ -f $mkdocs_config ];then
            if grep -q "custom_dir" $mkdocs_config; then
                log_info "有 custom_dir"
                grep "custom_dir" $mkdocs_config
                overrides_dir=`grep "custom_dir" $mkdocs_config |awk -F':' '{print $NF}'|tr -d ' '`
                log_info "overrides_dir => $overrides_dir"
                
                cat $mkdocs_config
                break
            else
                sed -i "/theme:/a \ \ custom_dir: overrides" $mkdocs_config
                
                cat $mkdocs_config
                break
                
            fi
        fi
    done
  
    [ -d ${overrides_dir} ] || mkdir -p ${overrides_dir}
    cat > ${overrides_dir}/main.html <<EOF
{% extends "base.html" %}
{% block scripts %}
  <script defer src="https://umami.cncfstack.com/script.js" data-website-id="${umami_website_id}"></script>
  <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1160147761715358" data-overlays="collapsed-bottom" crossorigin="anonymous"> </script>
  <script>(adsbygoogle = window.adsbygoogle || []).push({});</script>
{% endblock %}
  
{% block htmltitle %}
  <title>${theme}</title>
{% endblock %}
 
{% block styles %}
  {{ super() }}

<style> body {padding-bottom: 0 !important;}</style>
{% endblock %}
EOF


   cat ${overrides_dir}/main.html
   set +x
}

add_head_assets_for_jeklly(){
    umami_website_id=$1
    theme=$2
    theme_version=$3
  
    # 将 </body> 前面添加
    # sed _layouts/default.html
    for jeklly in "_layouts/default.html" "todo"
    do
      if [ -f $jeklly ];then
        log_info "add_head_asset 匹配到文件：$jeklly"
        sed -i "s#</body>#<script defer src='https://umami.cncfstack.com/script.js' data-website-id='${umami_website_id}'></script>  <script async src='https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1160147761715358' data-overlays='collapsed-bottom' crossorigin='anonymous'> </script><script>(adsbygoogle = window.adsbygoogle || []).push({});</script><style> body {padding-bottom: 0 !important;}</style></body>#g"  $jeklly
      fi
    done
    cat _layouts/default.html

}

add_head_assets_for_hugo(){
  
  umami_website_id=$1
  theme=$2
  theme_version=$3

  hugo_done="false"
  # Argifacehub => themes/hugo-geekdoc/layouts/_default/baseof.html
  for hugo_file in "layouts/_default/baseof.html" "layouts/baseof.html"  "themes/docsy-overrides/layouts/baseof.html" "themes/containerd/layouts/_default/baseof.html" "themes/geekboot/layouts/_default/baseof.html" "themes/buildpacks/layouts/_default/baseof.html" "themes/hugo-geekdoc/layouts/_default/baseof.html"
  do
      if [ -f $hugo_file ];then
          log_info "add_head_asset 匹配到文件：$hugo_file"
          sed -i "s#</body>#<script defer src='https://umami.cncfstack.com/script.js' data-website-id='${umami_website_id}'></script>  <script async src='https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1160147761715358' data-overlays='collapsed-bottom' crossorigin='anonymous'> </script><script>(adsbygoogle = window.adsbygoogle || []).push({});</script><style> body {padding-bottom: 0 !important;}</style></body>#g" $hugo_file
          cat $hugo_file

          hugo_done="true"
          break 
      fi
  done

  # 如果默认的文件已经修改成功了，后面的代码不需要执行了
  if [ "${hugo_done}" = "true" ];then
      log_info "有基础 baseof.html"
      return
  fi


  # 特殊情况，没有到知道 baseof 文件时，从其他文件中添加。但是这些文件可能会添加到 head 中，影响页面加载性能
  if [ -f layouts/_partials/head.html ];then
    echo_google_ads "layouts/_partials/head.html"
    echo '<script defer src="https://umami.cncfstack.com/script.js" data-website-id="'${umami_website_id}'"></script>' >> layouts/_partials/head.html
    cat layouts/_partials/head.html
  
  elif [ -f layouts/partials/head.html ];then
    echo_google_ads "layouts/partials/head.html"
    echo '<script defer src="https://umami.cncfstack.com/script.js" data-website-id="'${umami_website_id}'"></script>'  >> layouts/partials/head.html
    cat layouts/partials/head.html

  # in-toto 需要使用这个文件
  elif [ -f layouts/_partials/favicons.html ];then
    echo_google_ads "layouts/_partials/favicons.html"
    echo '<script defer src="https://umami.cncfstack.com/script.js" data-website-id="'${umami_website_id}'"></script>'  >> layouts/_partials/favicons.html
    cat layouts/_partials/favicons.html

  # dapr 需要使用这个文件
  elif [ -f daprdocs/layouts/_partials/hooks/body-end.html ];then
    echo_google_ads "daprdocs/layouts/_partials/hooks/body-end.html"
    echo '<script defer src="https://umami.cncfstack.com/script.js" data-website-id="'${umami_website_id}'"></script>' >> daprdocs/layouts/_partials/hooks/body-end.html
    cat daprdocs/layouts/_partials/hooks/body-end.html
  
  elif [ -f layouts/_partials/layouts/head/head.html ];then
    echo_google_ads "layouts/_partials/layouts/head/head.html"
    echo '<script defer src="https://umami.cncfstack.com/script.js" data-website-id="'${umami_website_id}'"></script>'  >> layouts/_partials/layouts/head/head.html
    cat layouts/_partials/layouts/head/head.html

  elif [ -f layouts/partials/meta.html ];then
    echo_google_ads "layouts/partials/meta.html"
    echo '<script defer src="https://umami.cncfstack.com/script.js" data-website-id="'${umami_website_id}'"></script>'  >> layouts/partials/meta.html
    cat layouts/partials/meta.html

  elif [ -f layouts/partials/head_custom.html ];then
    echo_google_ads "layouts/partials/head_custom.html"
    echo '<script defer src="https://umami.cncfstack.com/script.js" data-website-id="'${umami_website_id}'"></script>'  >> layouts/partials/head_custom.html
    cat layouts/partials/head_custom.html

  elif [ -f themes/le-2025/layouts/partials/head.html ];then
    echo_google_ads "themes/le-2025/layouts/partials/head.html"
    echo '<script defer src="https://umami.cncfstack.com/script.js" data-website-id="'${umami_website_id}'"></script>'  >> themes/le-2025/layouts/partials/head.html
    cat themes/le-2025/layouts/partials/head.html

  elif [ -f layouts/partials/head-js.html ];then
    echo_google_ads "layouts/partials/head-js.html"
    echo '<script defer src="https://umami.cncfstack.com/script.js" data-website-id="'${umami_website_id}'"></script>'  >> layouts/partials/head-js.html
    cat layouts/partials/head-js.html
  
  elif [ -f layouts/partials/head-meta.html ];then
    echo_google_ads "layouts/partials/head-meta.html"
    echo '<script defer src="https://umami.cncfstack.com/script.js" data-website-id="'${umami_website_id}'"></script>'  >> layouts/partials/head-meta.html
    cat layouts/partials/head-meta.html
      
  elif [ -f layouts/partials/head-css.html ];then
    echo_google_ads "layouts/partials/head-css.html"
    echo '<script defer src="https://umami.cncfstack.com/script.js" data-website-id="'${umami_website_id}'"></script>'  >> layouts/partials/head-css.html
    cat layouts/partials/head-css.html

  elif [ -f layouts/partials/favicon.html ];then
    echo_google_ads "layouts/partials/favicon.html"
    echo '<script defer src="https://umami.cncfstack.com/script.js" data-website-id="'${umami_website_id}'"></script>'  >> layouts/partials/favicon.html
    cat layouts/partials/favicon.html

  elif [ -f layouts/partials/favicons.html ];then
    echo_google_ads "layouts/partials/favicons.html"
    echo '<script defer src="https://umami.cncfstack.com/script.js" data-website-id="'${umami_website_id}'"></script>'  >> layouts/partials/favicons.html
    cat layouts/partials/favicons.html

  elif [ -f layouts/partials/hooks/head-end.html ];then
    echo_google_ads "layouts/partials/hooks/head-end.html"
    echo '<script defer src="https://umami.cncfstack.com/script.js" data-website-id="'${umami_website_id}'"></script>'  >> layouts/partials/hooks/head-end.html
    cat layouts/partials/hooks/head-end.html

  elif [ -f layouts/_partials/scripts/mermaid.html ];then
    echo_google_ads "layouts/_partials/scripts/mermaid.html"
    echo '<script defer src="https://umami.cncfstack.com/script.js" data-website-id="'${umami_website_id}'"></script>'  >> layouts/_partials/scripts/mermaid.html
    cat layouts/_partials/scripts/mermaid.html

  elif [ -f layouts/partials/hooks/head-end.html ];then
    echo_google_ads "layouts/partials/hooks/head-end.html"
    echo '<script defer src="https://umami.cncfstack.com/script.js" data-website-id="'${umami_website_id}'"></script>'  >> layouts/partials/hooks/head-end.html
    cat layouts/partials/hooks/head-end.html

  elif [ -f layouts/partials/javascript.html ];then
    echo_google_ads "layouts/partials/javascript.html"
    echo '<script defer src="https://umami.cncfstack.com/script.js" data-website-id="'${umami_website_id}'"></script>'  >> layouts/partials/javascript.html
    cat layouts/partials/javascript.html

  elif [ -f layouts/partials/hooks/body-end.html ];then
    echo_google_ads "layouts/partials/hooks/body-end.html"
    echo '<script defer src="https://umami.cncfstack.com/script.js" data-website-id="'${umami_website_id}'"></script>'  >> layouts/partials/hooks/body-end.html
    cat layouts/partials/hooks/body-end.html
  
  else
    log_error "Hugo 的项目，但是没有找到合适的 add_head_assets 文件"
  fi

  log_warn "testteetetettetewtestteetetettetewtetetetetetetettetetetetetetet"
}



  
add_head_assets_for_astro(){
  umami_website_id=$1
  theme=$2
  theme_version=$3
  
  for astro in "src/layouts/DefaultLayout.astro" "todo"
  do
    if [ -f $astro ];then
      sed -i "s#</body>#<script defer src='https://umami.cncfstack.com/script.js' data-website-id='${umami_website_id}'></script>  <script async src='https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1160147761715358' data-overlays='collapsed-bottom' crossorigin='anonymous'> </script><script>(adsbygoogle = window.adsbygoogle || []).push({});</script><style> body {padding-bottom: 0 !important;}</style></body>#g" $astro
    fi
    break
  done
}

# module.exports = {
#   plugins: [
#     () => ({
#       name: 'ads-umami-style',
#       injectHtmlTags: () => ({
#         headTags: [
#           // Google AdSense 脚本
#           {
#             tagName: 'script',
#             attributes: {
#               async: true,
#               src: 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1160147761715358',
#               'data-overlays': 'collapsed-bottom',
#               crossorigin: 'anonymous'
#             }
#           },
#           // AdSense 初始化
#           {
#             tagName: 'script',
#             innerHTML: '(adsbygoogle = window.adsbygoogle || []).push({});'
#           },
#           // 样式调整
#           {
#             tagName: 'style',
#             innerHTML: 'body {padding-bottom: 0 !important;}'
#           },
#           // Umami 分析脚本
#           {
#             tagName: 'script',
#             attributes: {
#               defer: true,
#               src: 'https://umami.cncfstack.com/script.js',
#               'data-website-id': 'bf711965-231e-4ff8-9620-75f4b7a6256e'
#             }
#           }
#         ]
#       })
#     }),
#     // ...其他插件
#   ]
# };
#sed -i "s#plugins:\s*\[#plugins: [()=>({name:'ads-umami-style',injectHtmlTags:()=>({headTags:[{tagName:'script',attributes:{async:true,src:'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1160147761715358','data-overlays':'collapsed-bottom',crossorigin:'anonymous'}},{tagName:'script',innerHTML:'(adsbygoogle = window.adsbygoogle || []).push({});'},{tagName:'style',innerHTML:'body {padding-bottom: 0 !important;}'},{tagName:'script',attributes:{defer:true,src:'https://umami.cncfstack.com/script.js','data-website-id':'${umami_website_id}'}}]})}),#g" docusaurus.config.js

add_head_assets_for_docusaurus(){
  umami_website_id=$1
  theme=$2
  theme_version=$3

  docusaurus_done="false"
                  

  for docusaurus in "docusaurus.config.js" "docusaurus.config.ts"
  do
    if [ -f $docusaurus ];then
       if grep -q "plugins:" $docusaurus; then
          sed -i "s#plugins:\s*\[#plugins: [()=>({name:'ads-umami-style',injectHtmlTags:()=>({headTags:[{tagName:'script',attributes:{async:true,src:'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1160147761715358','data-overlays':'collapsed-bottom',crossorigin:'anonymous'}},{tagName:'script',innerHTML:'(adsbygoogle = window.adsbygoogle || []).push({});'},{tagName:'style',innerHTML:'body {padding-bottom: 0 !important;}'},{tagName:'script',attributes:{defer:true,src:'https://umami.cncfstack.com/script.js','data-website-id':'${umami_website_id}'}}]})}),#g" $docusaurus
          docusaurus_done="true"
          log_info "在配置文件中有plugins字段"
          break
        else
          #sed -i "/theme:/a \ \ custom_dir: overrides" $mkdocs_config
          sed -i "/baseUrl:/a \ \ plugins: [()=>({name:'ads-umami-style',injectHtmlTags:()=>({headTags:[{tagName:'script',attributes:{async:true,src:'https:\/\/pagead2.googlesyndication.com\/pagead\/js\/adsbygoogle.js?client=ca-pub-1160147761715358','data-overlays':'collapsed-bottom',crossorigin:'anonymous'}},{tagName:'script',innerHTML:'(adsbygoogle = window.adsbygoogle || []).push({});'},{tagName:'style',innerHTML:'body {padding-bottom: 0 !important;}'},{tagName:'script',attributes:{defer:true,src:'https:\/\/umami.cncfstack.com\/script.js','data-website-id':'${umami_website_id}'}}]})})]," $docusaurus
          #sed -i "s/baseUrl/xxxxxxxxx/g" $docusaurus
          docusaurus_done="true"
          log_info "在配置文件中没有plugins字段，新增该配置"
          break
        fi
    fi
  done
  
  # 如果默认的文件已经修改成功了，后面的代码不需要执行了
  if [ "${docusaurus_done}" = "true" ];then
      log_info "找到 docusaurus 相关配置文件"
      return
  fi

  log_error "没有找到 docusaurus 相关配置文件，无法处理"
}

  
# arg1: umami_website_id:  umami中网站的id
# arg2: theme 主题类型，hugo、docsy、jeklly、mkdoc等 || 但是如果是 mkdocs，theme 则为项目名称 title
#   1.hugo: 表示没有使用任何主题，如 hugo官网
#。 2.docsy: 表示使用的是 docsy主题
# arg3: theme_version 用于指定在没有head.html文件时提供一个相对准确的 docsy 版本文件
add_head_assets() {
  umami_website_id=$1
  theme=$2
  theme_version=$3

  ########################################
  # mkdos.yaml 是 mkdoc、mkdocs-material 的配置文件
  if [ -f mkdocs.yaml -o -f mkdocs.yml ];then
      add_head_assets_for_mkdocs $umami_website_id $theme $theme_version
      return
  fi

  ########################################
  # Gemfile 是判断是否为 Jeklly 的项目
  if [ -f Gemfile ];then
    add_head_assets_for_jeklly $umami_website_id $theme $theme_version
    return
  fi

  # Hugo
  ########################################
  # layouts/_default/baseof.html => docker
  # ayouts/baseof.html => hugo docsy 
  #if [ -f hugo.yaml -o -f hugo.toml -o -f config.yaml -o -f config.toml -o -f config/_default/hugo.yaml -o -f config/_default/hugo.yml ];then
  #  add_head_assets_for_hugo $umami_website_id $theme $theme_version
  #  return
  #fi


  pwd
  ls -lha 
  # 检查更多可能的 Hugo 配置文件位置
  if [ -f hugo.yaml ] || \
     [ -f hugo.toml ] || \
     [ -f hugo.json ] || \
     [ -f hugo.yml ] || \
     [ -f config.yaml ] || \
     [ -f config.yml ] || \
     [ -f config.toml ] || \
     [ -f config.json ] || \
     [ -f config/_default/hugo.yaml ] || \
     [ -f config/_default/hugo.yml ] || \
     [ -f config/_default/hugo.toml ] || \
     [ -f config/_default/hugo.json ]; then
      add_head_assets_for_hugo $umami_website_id $theme $theme_version
      return
  fi

  ########################################
  # astro.config.mjs => kyverno
  if [ -f astro.config.mjs ];then
    add_head_assets_for_astro $umami_website_id $theme $theme_version
    return
  fi

  ########################################
  # docusaurus
  if [ -f docusaurus.config.js -o -f docusaurus.config.ts ];then
    add_head_assets_for_docusaurus  $umami_website_id $theme $theme_version
    return
  fi

  log_error "New V3版本没有兼容"
  
  
 
      log_warn "没有找到合适的 head.html 文件"

      if [ "$theme" = "hugo" ];then
            log_info "head文件不存在，但是匹配到 hugo 主题"
            [[ ! -d layouts/_partials/layouts/head ]] || mkdir -p layouts/_partials/layouts/head
            # 如果没有提供版本，使用最新的版本, 格式如：v0.148.0
            if [ -z $theme_version ];then
                curl -fsSL https://raw.githubusercontent.com/gohugoio/hugoDocs/refs/heads/master/layouts/_partials/layouts/head/head.html -o layouts/_partials/layouts/head/head.html
            else
                curl -fsSL https://raw.githubusercontent.com/gohugoio/hugoDocs/refs/tags/v${theme_version}/layouts/_partials/layouts/head/head.html -o layouts/_partials/layouts/head/head.html
            fi
            
            echo_google_ads "layouts/_partials/layouts/head/head.html"
            echo '<script defer src="https://umami.cncfstack.com/script.js" data-website-id="'${umami_website_id}'"></script>'  >> layouts/_partials/layouts/head/head.html
            cat layouts/_partials/layouts/head/head.html

      elif [ "$theme" = "docsy" ];then
    
            log_info "head文件不存在，但是匹配到 docsy 主题"
              
            [[ -d layouts/_partials ]] || mkdir -p layouts/_partials
        
            # 如果没有提供docsy版本，使用最新的版本，格式如 v0.13.0
            if [ -z $theme_version ];then
              curl -fsSL https://raw.githubusercontent.com/google/docsy/refs/heads/main/layouts/_partials/head.html -o layouts/_partials/head.html
            else
              curl -fsSL https://raw.githubusercontent.com/google/docsy/refs/tags/${theme_version}/layouts/_partials/head.html -o layouts/_partials/head.html
            fi
          
            echo_google_ads "layouts/_partials/head.html"
            echo '<script defer src="https://umami.cncfstack.com/script.js" data-website-id="'${umami_website_id}'"></script>'  >> layouts/_partials/head.html
            cat layouts/_partials/head.html

      else
         log_error "hugo_add_head 异常，不支持的主题"
      fi


}





#install_hugo 0.152.2
install_hugo(){
    hugo_version=$1

  if [ -f /data/task/website/bin/hugo-$hugo_version ];then
    rm -f /usr/bin/hugo
    rm -f /bin/hugo
    ln -s /data/task/website/bin/hugo-$hugo_version /usr/bin/hugo
    ln -s /data/task/website/bin/hugo-$hugo_version /bin/hugo
    return 0
  fi

  
    num=$(echo "$hugo_version" | awk -F'.' '{print int($2)}')
  
    if [ -z "$hugo_version" ];then
        hugo_url="https://github.com/gohugoio/hugo/releases/download/v0.133.0/hugo_extended_0.133.0_linux-${cpu_arch}.tar.gz"
    else
        if [ $num -gt 108 ];then
          hugo_url="https://github.com/gohugoio/hugo/releases/download/v${hugo_version}/hugo_extended_${hugo_version}_linux-${cpu_arch}.tar.gz"
        else
              if [ "$cpu_arch" = "arm64"  ];then
                hugo_url="https://github.com/gohugoio/hugo/releases/download/v${hugo_version}/hugo_extended_${hugo_version}_Linux-ARM64.tar.gz"
            else
                hugo_url="https://github.com/gohugoio/hugo/releases/download/v${hugo_version}/hugo_extended_${hugo_version}_Linux-64bit.tar.gz"
            fi
        fi
    fi
    
    pkg_name=`echo $hugo_url|awk -F'/' '{print $NF}'`

    log_info "下载并安装 hugo: $pkg_name"
    wget -q  $hugo_url -O $pkg_name
    tar xf $pkg_name

    [ -d /data/task/website/bin ] || mkdir -p data/task/website/bin
    sudo cp hugo /data/task/website/bin/hugo-${$hugo_version}
    sudo chmod +x /data/task/website/bin/hugo-${$hugo_version}

    rm -f /usr/bin/hugo
    rm -f /bin/hugo
    ln -s /data/task/website/bin/hugo-$hugo_version /usr/bin/hugo
    ln -s /data/task/website/bin/hugo-$hugo_version /bin/hugo

    /usr/bin/hugo version
    if [ "$?" != "0" ];then
        log_error " hugo 安装失败: /usr/bin/hugo 文件不存在或者没有成功设置可执行权限"
    fi
}

install_hugo_v57_2(){  
    install_hugo "https://github.com/gohugoio/hugo/releases/download/v0.57.2/hugo_extended_0.57.2_Linux-64bit.tar.gz" 
}

install_hugo_v65_3(){  
    install_hugo "https://github.com/gohugoio/hugo/releases/download/v0.65.3/hugo_extended_0.65.3_Linux-64bit.tar.gz" 
}
install_hugo_v66(){    
    install_hugo "https://github.com/gohugoio/hugo/releases/download/v0.66.0/hugo_extended_0.66.0_Linux-64bit.tar.gz" 
}
install_hugo_v68_3(){  
    install_hugo "https://github.com/gohugoio/hugo/releases/download/v0.68.3/hugo_extended_0.68.3_Linux-64bit.tar.gz" 
}
install_hugo_v74(){    
    install_hugo "https://github.com/gohugoio/hugo/releases/download/v0.74.0/hugo_extended_0.74.0_Linux-64bit.tar.gz" 
}
install_hugo_v80(){    
    install_hugo "https://github.com/gohugoio/hugo/releases/download/v0.80.0/hugo_extended_0.80.0_Linux-64bit.tar.gz" 
}
install_hugo_v83_1(){  
    install_hugo "https://github.com/gohugoio/hugo/releases/download/v0.83.1/hugo_extended_0.83.1_Linux-64bit.tar.gz" 
}
install_hugo_v93_2(){  
    install_hugo "https://github.com/gohugoio/hugo/releases/download/v0.93.2/hugo_extended_0.93.2_Linux-64bit.tar.gz" 
}
install_hugo_v99_1(){  
    install_hugo "https://github.com/gohugoio/hugo/releases/download/v0.99.1/hugo_extended_0.99.1_Linux-64bit.tar.gz" 
}
install_hugo_v100_2(){ 
    install_hugo "https://github.com/gohugoio/hugo/releases/download/v0.100.2/hugo_extended_0.100.2_Linux-64bit.tar.gz" 
}
install_hugo_v102_3(){ 
    install_hugo "https://github.com/gohugoio/hugo/releases/download/v0.102.3/hugo_extended_0.102.3_Linux-64bit.tar.gz" 
}
install_hugo_v108(){   
    install_hugo "https://github.com/gohugoio/hugo/releases/download/v0.108.0/hugo_extended_0.108.0_Linux-64bit.tar.gz" 
}
install_hugo_v111_3(){ 
    install_hugo "https://github.com/gohugoio/hugo/releases/download/v0.111.3/hugo_extended_0.111.3_linux-amd64.tar.gz" 
}
install_hugo_v114(){   
    install_hugo "https://github.com/gohugoio/hugo/releases/download/v0.114.0/hugo_extended_0.114.0_linux-amd64.tar.gz" 
}
install_hugo_v119(){   
    install_hugo "https://github.com/gohugoio/hugo/releases/download/v0.119.0/hugo_extended_0.119.0_linux-amd64.tar.gz" 
}
install_hugo_v120(){   
    install_hugo "https://github.com/gohugoio/hugo/releases/download/v0.120.0/hugo_extended_0.120.0_linux-amd64.tar.gz" 
}
install_hugo_v122(){   
    install_hugo "https://github.com/gohugoio/hugo/releases/download/v0.122.0/hugo_extended_0.122.0_linux-amd64.tar.gz" 
}
install_hugo_v124_1(){ 
    install_hugo "https://github.com/gohugoio/hugo/releases/download/v0.124.1/hugo_extended_0.124.1_linux-amd64.tar.gz" 
}
install_hugo_v130(){ 
    install_hugo "https://github.com/gohugoio/hugo/releases/download/v0.130.0/hugo_extended_0.130.0_linux-amd64.tar.gz" 
}
install_hugo_v133(){ 
    install_hugo "https://github.com/gohugoio/hugo/releases/download/v0.133.0/hugo_extended_0.133.0_linux-amd64.tar.gz" 
}
install_hugo_v136_5(){ 
    install_hugo "https://github.com/gohugoio/hugo/releases/download/v0.136.5/hugo_extended_0.136.5_linux-amd64.tar.gz" 
}
install_hugo_v139_3(){ 
    install_hugo "https://github.com/gohugoio/hugo/releases/download/v0.139.3/hugo_extended_0.139.3_linux-amd64.tar.gz" 
}
install_hugo_v143_1(){ 
    install_hugo "https://github.com/gohugoio/hugo/releases/download/v0.143.1/hugo_extended_0.143.1_linux-amd64.tar.gz" 
}
install_hugo_v145(){   
    install_hugo "https://github.com/gohugoio/hugo/releases/download/v0.145.0/hugo_extended_0.145.0_linux-amd64.tar.gz" 
}


install_postcss(){
    log_info "安装 postCSS"
    npm i -D postcss postcss-cli autoprefixer
}



check_cdn_change(){
    log_info "=============================================> 以下文件进行了 cdn 替换，请确认文件在 https://cdn.cncfstack.com 是否存在"
    grep "filetoto.cncfstack.com" ./* -R |grep -v "otocn\.sed"|awk -F':' '{print $1}'
}


check_not_change(){
    log_info "=============================================> 以下可能的外部文件未被处理"
    # 有些图标表情使用 CDN 的 SVG，这类也可以代理。TODO：有些svg中会包含地址，这类是不需要处理的，但是会grep出来。不移除会有大量的无效信息，还是不显示svg内容，根据实际情况单独处理
    # raw.githubusercontent.com 是 github 的内容，太多输出了，有依赖单独处理吧
    grep -iEo "(maxcdn.bootstrapcdn.com|code.jquery.com|cdnjs.cloudflare.com|cdn-images.mailchimp.com|cdn.jsdelivr.net|fonts.googleapis.com|unpkg.com|www.googletagmanager.com)" ./* -R |grep -vE "(\.sh\:|\.md\:|\.toml|index\.rss\.xml|README\.txt\:|otocn\.sed\:|\.svg\:|node_modules)" 
}


# find_and_sed(){
#     # 查找可能存在外部地址的文件，
#     # 对于其他文件即使包含外部地址也不需要处理，比如 svg 图片中的google字体地址
#     find  . -type f \( -iname "*.txt" \
#         -o -iname "*.md" \
#         -o -iname "*.toml" \
#         -o -iname "*.js" \
#         -o -iname "*.mjs" \
#         -o -iname "*.html" \
#         -o -iname "*.css" \
#         -o -iname "*.sass" \
#         -o -iname "*.scss" \
#         -o -iname "*.tpl" \
#         -o -iname "*.rst" \) > ${workdir}/filelist

#     cat ${workdir}/../sed/* > ${workdir}/../toto.sed

#     # 循环依次处理可能包含外部链接的文件，并进行替换
#     for file in `cat ${workdir}/filelist`
#     do
#         sudo sed -i -f toto.sed $file
#     done

#     check_cdn_change
#     check_not_change
# }

# 可以指定处理的路径，这在构建完成后再进行替换时很有用
find_and_sed_v2(){
    path=$1
    # 查找可能存在外部地址的文件，
    # 对于其他文件即使包含外部地址也不需要处理，比如 svg 图片中的google字体地址
    find  $path -type f -iname "*.txt" \
        -o -iname "*.md" \
        -o -iname "*.toml" \
        -o -iname "*.js" \
        -o -iname "*.mjs" \
        -o -iname "*.html" \
        -o -iname "*.css" \
        -o -iname "*.sass" \
        -o -iname "*.scss" \
        -o -iname "*.tpl" \
        -o -iname "*.rst" > wil-sed-file-list

    cat ../sed/* > toto.sed

    # 循环依次处理可能包含外部链接的文件，并进行替换
    for file in `cat wil-sed-file-list`
    do
        sudo sed -i -f toto.sed $file
    done

    check_cdn_change
    #check_not_change
}



find_and_sed_v3(){
    path=$1

    log_info “查找可能存在外部地址的文件，对于其他文件即使包含外部地址也不需要处理，比如 svg 图片中的google字体地址”
    # find  $path -type f -iname "*.txt" \
    #     -o -iname "*.md" \
    #     -o -iname "*.toml" \
    #     -o -iname "*.js" \
    #     -o -iname "*.mjs" \
    #     -o -iname "*.html" \
    #     -o -iname "*.css" \
    #     -o -iname "*.sass" \
    #     -o -iname "*.scss" \
    #     -o -iname "*.tpl" \
    #     -o -iname "*.rst" > wil-sed-file-list

    find  $path -type f > wil-sed-file-list

    log_info "通过find查找到需要进行替换的文件列表："
    cat wil-sed-file-list

    log_info "获取替换的 sed 文件："
    curl -fsSL https://raw.githubusercontent.com/cncfstack/filetoto/refs/heads/main/allfile.list -o allfile.list
    curl -fsSL https://raw.githubusercontent.com/cncfstack/filetoto/refs/heads/main/alldomains -o alldomains

    cat allfile.list|awk -F'https://' '{print "s|"$0"|https://filetoto.cncfstack.com/"$2"|g"}' > toto.sed
    cat alldomains|awk -F'https://' '{print "s|"$0"|https://filetoto.cncfstack.com/"$2"|g"}' >> toto.sed

    cat toto.sed

    # 循环依次处理可能包含外部链接的文件，并进行替换
    for file in `cat wil-sed-file-list`
    do
        log_info "正在 sed 处理文件：$file"
        sudo sed -i -f toto.sed $file
    done

    ##log_info "以下文件内容进行了替换"
    #grep "filetoto.cncfstack.com"  $path  -R 

}

install_aliyun_ossutil(){
  if [ ! -f ./ossutil ];then
    log_info "当前路径下无 ossutil，下载并安装到本地 ./ossutil 和 /usr/bin/ossutil"
    wget -q -O /tmp/ossutil-2.0.6-beta.01091200-linux-amd64.zip  https://gosspublic.alicdn.com/ossutil/v2-beta/2.0.6-beta.01091200/ossutil-2.0.6-beta.01091200-linux-amd64.zip
    unzip /tmp/ossutil-2.0.6-beta.01091200-linux-amd64.zip -d  /tmp
    cp /tmp/ossutil-2.0.6-beta.01091200-linux-amd64/ossutil ./ossutil
    chmod +x ./ossutil
    sudo cp ./ossutil /usr/bin/
  fi
}

debug_tools(){
    log_info "===debug info"
    ls -lha
    pwd
    log_info "===debug info"
}


cycle_sed(){
    path=$1

    find $path  -type f > /tmp/sed-file-list

    log_info "/tmp/sed-file-list 文件内容"
    cat /tmp/sed-file-list

    curl -fsSL https://raw.githubusercontent.com/cncfstack/filetoto/refs/heads/main/allfile.list -o /tmp/allfile.list
    curl -fsSL https://raw.githubusercontent.com/cncfstack/filetoto/refs/heads/main/alldomains -o /tmp/alldomains
    curl -fsSL https://raw.githubusercontent.com/cncfstack/filetoto/refs/heads/main/special.list -o /tmp/special.list

    cat /tmp/allfile.list|awk -F'https://' '{print "s|"$0"|https://filetoto.cncfstack.com/"$2"|g"}' > /tmp/toto.sed
    cat /tmp/alldomains|awk -F'https://' '{print "s|"$0"|https://filetoto.cncfstack.com/"$2"|g"}' >> /tmp/toto.sed
    cat /tmp/special.list >> /tmp/toto.sed

    log_info "/tmp/toto.sed 文件内容"
    cat /tmp/toto.sed

    # 循环依次处理可能包含外部链接的文件，并进行替换
    for file in `cat /tmp/sed-file-list`
    do
        file -b $file |grep "text"
        if [ $? -ne 0 ];then
            echo "not ASCII text, Just Skip: $file"
            continue
        fi
        sudo sed -i -f /tmp/toto.sed $file

        # 部分CSS引用时会添加完整性校验，修改了文件后不删除校验会导致浏览器拒绝处理
        sed -i 's/integrity="[^"]*"//g' $file

        log_info "$file 文件被替换"
        cat $file
    done
}


filetoto(){

    path=$1

    find $path  -type f > /tmp/sed-file-list

    log_info "/tmp/sed-file-list 文件内容的行数"
    cat /tmp/sed-file-list | wc -l

    curl -fsSL https://raw.githubusercontent.com/cncfstack/filetoto/refs/heads/main/static.file -o /tmp/static.file
    curl -fsSL https://raw.githubusercontent.com/cncfstack/filetoto/refs/heads/main/special.file-and-sed -o /tmp/special.file-and-sed

    cat /tmp/static.file|awk -F'https://' '{print "s|"$0"|https://filetoto.cncfstack.com/"$2"|g"}' > /tmp/toto.sed
    cat /tmp/special.file-and-sed >> /tmp/toto.sed


    log_info "/tmp/toto.sed 文件内容的行数"
    cat /tmp/toto.sed | wc -l

    # 循环依次处理可能包含外部链接的文件，并进行替换
    for file in `cat /tmp/sed-file-list`
    do
        file -b $file |grep "text"
        if [ $? -ne 0 ];then
            log_info "NOT ASCII text, Just Skip: $file"
            continue
        fi
        sudo sed -i -f /tmp/toto.sed $file  &>/dev/null

        # 部分CSS引用时会添加完整性校验，修改了文件后不删除校验会导致浏览器拒绝处理
        sed -i 's/integrity="[^"]*"//g' $file  &>/dev/null

        #,script.integrity="sha256-waClS2re9NUbXRsryKoof+F9qc1gjjIhc2eT7ZbIv94=",script.crossOrigin="anonymous"
        # jaeger 中通过脚本的方式生成脚本，需要单独处理
        sed -i 's/\,script\.integrity="[^"]*"//g' $file  &>/dev/null

        # Kubevir 中文档目录导航位置的体会
        sed -i 's|//kubevirt.io/user-guide|/user-guide/|g' $file  &>/dev/null
        
        log_info "$file 文件被替换"
        
    done
}

file_to_cn(){
    
    path=$1

    find $path  -type f > /tmp/sed-file-list

    log_info "/tmp/sed-file-list 文件内容的行数"
    cat /tmp/sed-file-list | wc -l

    # 循环依次处理可能包含外部链接的文件，并进行替换
    for file in `cat /tmp/sed-file-list`
    do
        file -b $file |grep "text"
        if [ $? -ne 0 ];then
            log_info "NOT ASCII text, Just Skip: $file"
            continue
        fi
        sudo sed -i -f domain.sed $file  &>/dev/null
    done

}

commitid_check(){
    commitid_path=$1
    log_info "如果文件不存在就创建一个，防止下文的 cat 时文件不存在报错: ${commitid_path}"
    [ -f $commitid_path ] || echo 'create-new-commidid-file' > $commitid_path

    new_commitid=$(git rev-parse HEAD)
    old_commitid=$(cat $commitid_path)

    log_info "新的 commitid，当前Clone代码的 CommitID：${new_commitid}"
    log_info "旧的 commitid，数据文件中保存的 CommitID：${old_commitid}"

    if [ "${new_commitid}" = "${old_commitid}" ];then
        log_info "commitid 没有发生变化，内容没有更新，退出本次项目"
        log_warn "common.sh: CommitID 相同，跳过构建."

        # 创建一个文件，用于跳过 Github Action 执行
        touch /tmp/website-skip

        # exit 退出到 build.sh 中 find 执行脚本
        exit 0
    else
        log_info "commitid 发生变化，开始构建"
    fi
}

commitid_save(){
    commitid_path=$1
    new_commitid=$(git rev-parse HEAD)
    echo "${new_commitid}" > $commitid_path
}
