# 工作流的名称
name: CheckScores

# 工作流运行的名称
run-name: ${{ github.workflow }} ${{ github.sha }}

# 指定此工作流的触发器
on:
  schedule:
    - cron: "*/30 * * * *" # 每30分钟自动执行一次
  workflow_dispatch: # 可以手动执行
    inputs:
      force_push_message:
        # 如果为True，则当次运行时无论成绩是否已更新，都会进行推送
        description: "Whether or not to force a push message?"
        required: true
        default: "False"
        type: choice
        options:
          - "True"
          - "False"

jobs:
  # 检查成绩
  CheckScores:
    name: CheckScores

    # 在最新版的Ubuntu系统上运行
    runs-on: ubuntu-latest

    steps:
      # 使用GitHub Actions提供的动作来检出代码库
      - name: Checkout Repository
        uses: actions/checkout@main

      - name: Configure Git
        run: |
          # 配置Git用户信息
          git config --global user.email "actions@github.com"
          git config --global user.name "GitHub Actions"

      # 配置Python环境
      - name: Set up Python
        uses: actions/setup-python@main
        with:
          python-version: "*"

      - name: Install dependencies
        run: |
          # 使用pip安装项目的依赖项
          pip install requests rsa pyquery

      - name: Get Connection
        run: |
          # 获取连接信息
          url="https://ifconfig.me/all"
          response=$(curl -s -X GET "$url")
          echo "$response"

      - name: Run main program
        id: run_main_program
        env:
          FORCE_PUSH_MESSAGE: ${{ github.event.inputs.force_push_message }}
          GITHUB_ACTIONS: ${{github.actions}}
          URL: ${{ secrets.URL }}
          USERNAME: ${{ secrets.USERNAME }}
          PASSWORD: ${{ secrets.PASSWORD }}
          TOKEN: ${{ secrets.TOKEN }}
          GITHUB_REF_NAME: ${{ github.ref_name }}
          GITHUB_EVENT_NAME: ${{ github.event_name }}
          GITHUB_ACTOR: ${{ github.actor }}
          GITHUB_ACTOR_ID: ${{ github.actor_id }}
          GITHUB_TRIGGERING_ACTOR: ${{ github.triggering_actor }}
          REPOSITORY_NAME: ${{ github.repository }}
          GITHUB_SHA: ${{ github.sha }}
          GITHUB_WORKFLOW: ${{ github.workflow }}
          GITHUB_RUN_NUMBER: ${{ github.run_number }}
          GITHUB_RUN_ID: ${{ github.run_id }}
        run: |
          # 运行主程序
          # 判断环境变量是否为空
          if [ -z "$URL" ]; then
            echo "URL Secret is empty!"
            echo "::error title=URL Secret is empty!" \
            "::Your 'URL' Secret is not filled with any" \
            "information, so your program will not work!"
            Whether_Secret_is_empty=true
          fi
          if [ -z "$USERNAME" ]; then
            echo "USERNAME Secret is empty!"
            echo "::error title=USERNAME Secret is empty!" \
            "::Your 'USERNAME' Secret is not filled with any" \
            "information, so your program will not work!"
            Whether_Secret_is_empty=true
          fi
          if [ -z "$PASSWORD" ]; then
            echo "PASSWORD Secret is empty!"
            echo "::error title=PASSWORD Secret is empty!" \
            "::Your 'PASSWORD' Secret is not filled with any" \
            "information, so your program will not work!"
            Whether_Secret_is_empty=true
          fi
          if [ -z "$TOKEN" ]; then
            echo "TOKEN Secret is empty!"
            echo "::error title=TOKEN Secret is empty!" \
            "::Your 'TOKEN' Secret is not filled with any" \
            "information, so your program will not work!"
            Whether_Secret_is_empty=true
          fi
          if [ "$Whether_Secret_is_empty" = true ]; then
            echo "One or more Secrets are empty."
            exit 1
          fi

          # 判断是否需要强制推送信息
          if [ -z "${{ github.event.inputs.force_push_message }}" ]; then
            export FORCE_PUSH_MESSAGE="False"
          else
            export FORCE_PUSH_MESSAGE="${{ github.event.inputs.force_push_message }}"
          fi
          export BEIJING_TIME="$(TZ='Asia/Shanghai' date +'%Y-%m-%d %H:%M:%S:%3N')"
          echo "BEIJING_TIME=$BEIJING_TIME" >> $GITHUB_OUTPUT

          # 定义 mask_middle 函数，接收一个字符串作为输入参数
          mask_middle() {
            local input=$1  # 获取输入参数并赋值给局部变量 input
            local length=${#input}  # 计算输入字符串的长度并赋值给局部变量 length

            # 如果字符串长度小于等于3，则将其全部替换为 '*'
            if [ $length -le 3 ]; then
              echo $(printf '%*s' $length | tr ' ' '*')  # 使用 printf 和 tr 命令生成与长度相同数量的 '*'
            else
              local first=${input:0:1}  # 提取字符串的第一个字符并赋值给局部变量 first
              local last=${input: -1}  # 提取字符串的最后一个字符并赋值给局部变量 last
              local middle_length=$((length - 2))  # 计算中间部分的长度（除去首尾字符）
              local middle=$(printf '%*s' $middle_length | tr ' ' '*')  # 使用 printf 和 tr 命令生成与中间部分长度相同数量的 '*'
              echo "${first}${middle}${last}"  # 组合首字符、中间部分的 '*' 和尾字符，并输出结果
            fi
          }

          # 定义 anonymize_domain 函数，接收一个 URL 作为输入参数
          anonymize_domain() {
            local url=$1  # 获取输入参数并赋值给局部变量 url
            local protocol=$(echo "$url" | sed -n 's#^\(.*://\).*#\1#p')  # 提取协议部分（例如 http:// 或 https://）
            local rest=$(echo "${url#*://}")  # 去掉协议部分后的剩余部分
            local domain=$(echo "$rest" | sed 's#/.*##')  # 提取域名部分
            local path=$(echo "$rest" | sed 's#^[^/]*##')  # 提取路径部分

            # 将域名部分按 '.' 分割，并替换每个部分为相应数量的 '*'
            IFS='.' read -r -a domain_parts <<< "$domain"  # 按 '.' 分割域名部分为数组
            local anonymized_domain=""
            for part in "${domain_parts[@]}"; do
              anonymized_domain+=$(printf '%*s' ${#part} | tr ' ' '*').  # 使用 printf 和 tr 命令生成与部分长度相同数量的 '*'
            done
            anonymized_domain=${anonymized_domain%.}  # 移除最后一个多余的 '.'

            # 组合协议、匿名化后的域名和路径，输出结果
            echo "${protocol}${anonymized_domain}${path}"
          }

          LOGINURL="xtgl/login_slogin.html"

          # 方便通过截图快速定位到用户
          echo "Url: $(anonymize_domain "$URL")${LOGINURL}"  # 调用 anonymize_domain 函数处理 URL 并输出结果
          echo "Username: $(mask_middle "$USERNAME")"  # 调用 mask_middle 函数处理字符串并输出结果
          echo "Password: $(mask_middle "$PASSWORD")"  # 调用 mask_middle 函数处理字符串并输出结果
          echo "Force Push Message: $FORCE_PUSH_MESSAGE"
          echo "Branch Name: $GITHUB_REF_NAME"
          echo "Triggered By: $GITHUB_EVENT_NAME"
          echo "Initial Run By: $GITHUB_ACTOR"
          echo "Initial Run By ID: $GITHUB_ACTOR_ID"
          echo "Initiated Run By: $GITHUB_TRIGGERING_ACTOR"
          echo "Repository Name: $REPOSITORY_NAME"
          echo "Commit SHA: $GITHUB_SHA"
          echo "Workflow Name: $GITHUB_WORKFLOW"
          echo "Workflow Number: $GITHUB_RUN_NUMBER"
          echo "Workflow ID: $GITHUB_RUN_ID"
          echo "Beijing Time: $BEIJING_TIME"
          echo "Copyright © 2024 NianBroken. All rights reserved."
          echo "Author's website: https://www.nianbroken.top/"
          echo "Author's Repository URL: https://github.com/NianBroken/ZFCheckScores/"

          echo "------"
          # 运行主程序
          python main.py

      - name: Delete __pycache__ folder
        run: |
          # 删除__pycache__文件夹
          rm -rf __pycache__
          rm -rf scripts/__pycache__

      - name: Force push changes to the running branch
        run: |
          # 将更改强制推送到运行分支
          git add .
          git commit -m "Update from GitHub Actions" || true
          git push origin $GITHUB_REF_NAME --force