name: Update Docker Image Tags and Release Helm Chart

on:
  schedule:
    #- cron: "0 2 * * 1"  # 毎週月曜日 02:00 UTC
    - cron: "0 0 * * 0"  # 毎週日曜日 00:00 UTC
  workflow_dispatch:

jobs:
  update-and-release:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0  # 完全な履歴を取得

      - name: Check for new WordPress FPM Alpine version
        id: wordpress
        run: |
          set -e
          echo "Checking WordPress FPM Alpine versions..."
          CURRENT=$(grep -A3 "wordpress:" values.yaml | grep "tag:" | head -1 | sed 's/.*tag: *"\([^"]*\)".*/\1/' | tr -d ' ')
          echo "Current WordPress: $CURRENT"

          # Docker Hub API v2を使用してfpm-alpineタグを取得（全PHPバージョン対象）
          LATEST=$(curl -s "https://hub.docker.com/v2/repositories/library/wordpress/tags?page_size=100&name=fpm-alpine" | \
            jq -r '.results[].name' | \
            grep -E '^[0-9]+\.[0-9]+(\.[0-9]+)?-php[0-9]+\.[0-9]+-fpm-alpine$' | \
            grep -v 'rc' | \
            grep -v 'beta' | \
            grep -v 'alpha' | \
            sort -t- -k1,1V -k2,2V | \
            tail -n 1)

          if [ -z "$LATEST" ]; then
            echo "Warning: Could not fetch latest WordPress version, using current"
            LATEST="$CURRENT"
          fi

          # WordPressバージョンを抽出 (6.9.1の部分)
          APP_VERSION=$(echo "$LATEST" | grep -oE '^[0-9]+\.[0-9]+(\.[0-9]+)?')
          if [ -z "$APP_VERSION" ]; then
            echo "Warning: Could not extract WordPress version from: $LATEST"
            APP_VERSION=$(echo "$CURRENT" | grep -oE '^[0-9]+\.[0-9]+(\.[0-9]+)?')
          fi

          echo "Latest WordPress: $LATEST"
          echo "WordPress version: $APP_VERSION"

          # バージョン情報を分解して表示
        WP_VERSION=$(echo $LATEST | cut -d'-' -f1)
        PHP_VERSION=$(echo $LATEST | cut -d'-' -f2)
        echo "  WordPress: $WP_VERSION"
        echo "  PHP: $PHP_VERSION"
        echo "  Base: fpm-alpine"

          echo "current=$CURRENT" >> $GITHUB_OUTPUT
          echo "latest=$LATEST" >> $GITHUB_OUTPUT
          echo "app_version=$APP_VERSION" >> $GITHUB_OUTPUT

      - name: Check for new Nginx Alpine Perl version
        id: nginx
        run: |
          set -e
          echo "Checking Nginx Alpine Perl versions..."
          CURRENT=$(grep -A3 "nginx:" values.yaml | grep "tag:" | head -1 | sed 's/.*tag: *"\([^"]*\)".*/\1/' | tr -d ' ')
          echo "Current Nginx: $CURRENT"

          # Docker Hub API v2を使用してalphine-perlタグを取得
          LATEST=$(curl -s "https://hub.docker.com/v2/repositories/library/nginx/tags?page_size=100&name=alpine-perl" | \
            jq -r '.results[].name' | \
            grep -E '^[0-9]+\.[0-9]+\.[0-9]+-alpine-perl$' | \
            grep -v 'rc' | \
            grep -v 'beta' | \
            grep -v 'alpha' | \
            sort -V | \
            tail -n 1)

          if [ -z "$LATEST" ]; then
            echo "Warning: Could not fetch latest Nginx version, using current"
            LATEST="$CURRENT"
          fi
          echo "Latest Nginx: $LATEST"
          echo "current=$CURRENT" >> $GITHUB_OUTPUT
          echo "latest=$LATEST" >> $GITHUB_OUTPUT

      - name: Determine if update is needed
        id: check_update
        run: |
          set -e
          WP_CURRENT="${{ steps.wordpress.outputs.current }}"
          WP_LATEST="${{ steps.wordpress.outputs.latest }}"
          NGINX_CURRENT="${{ steps.nginx.outputs.current }}"
          NGINX_LATEST="${{ steps.nginx.outputs.latest }}"

          echo "WordPress: $WP_CURRENT vs $WP_LATEST"
          echo "Nginx: $NGINX_CURRENT vs $NGINX_LATEST"

          # 更新が必要かチェック
          UPDATE_NEEDED=false
          WP_UPDATED=false

          if [ "$WP_CURRENT" != "$WP_LATEST" ]; then
            UPDATE_NEEDED=true
            WP_UPDATED=true
            echo "WordPress update detected"
          fi

          if [ "$NGINX_CURRENT" != "$NGINX_LATEST" ]; then
            UPDATE_NEEDED=true
            echo "Nginx update detected"
          fi

          echo "update_needed=$UPDATE_NEEDED" >> $GITHUB_OUTPUT
          echo "wp_updated=$WP_UPDATED" >> $GITHUB_OUTPUT

          if [ "$UPDATE_NEEDED" = "true" ]; then
            echo "Update is needed"
          else
            echo "Already up to date - no action required"
          fi

      - name: Update values.yaml
        if: steps.check_update.outputs.update_needed == 'true'
        run: |
          set -e
          echo "Updating values.yaml..."

          # WordPress更新
          WP_OLD="${{ steps.wordpress.outputs.current }}"
          WP_NEW="${{ steps.wordpress.outputs.latest }}"
          if [ "$WP_OLD" != "$WP_NEW" ]; then
            sed -i "s|tag: \"${WP_OLD}\"|tag: \"${WP_NEW}\"|g" values.yaml
            echo "WordPress updated: $WP_OLD -> $WP_NEW"
          fi

          # Nginx更新
          NGINX_OLD="${{ steps.nginx.outputs.current }}"
          NGINX_NEW="${{ steps.nginx.outputs.latest }}"
          if [ "$NGINX_OLD" != "$NGINX_NEW" ]; then
            sed -i "s|tag: \"${NGINX_OLD}\"|tag: \"${NGINX_NEW}\"|g" values.yaml
            echo "Nginx updated: $NGINX_OLD -> $NGINX_NEW"
          fi

          echo "values.yaml updated"
          git diff values.yaml

      - name: Update Chart.yaml version
        if: steps.check_update.outputs.wp_updated == 'true'
        run: |
          set -e
          APP_VERSION="${{ steps.wordpress.outputs.app_version }}"
          sed -i "s/^version: .*/version: $APP_VERSION/" Chart.yaml
          sed -i "s/^appVersion: .*/appVersion: \"$APP_VERSION\"/" Chart.yaml
          echo "Chart.yaml updated to version $APP_VERSION"
          cat Chart.yaml

      - name: Commit changes
        if: steps.check_update.outputs.update_needed == 'true'
        run: |
          git config user.name "Gitea Actions Bot"
          git config user.email "actions@git.cafepieters.com"

          if [ "${{ steps.check_update.outputs.wp_updated }}" = "true" ]; then
            # WordPress更新時はChart.yamlも含める
            git add values.yaml Chart.yaml
            git commit -m "chore: update to WordPress ${{ steps.wordpress.outputs.app_version }}, nginx ${{ steps.nginx.outputs.latest }}"
          else
            # Nginxのみの更新時はvalues.yamlのみ
            git add values.yaml
            git commit -m "chore: update nginx to ${{ steps.nginx.outputs.latest }} (no release)"
          fi

          # プッシュをリトライ機構付きで実行
          MAX_RETRIES=3
          RETRY_COUNT=0
          until git push origin main || [ $RETRY_COUNT -eq $MAX_RETRIES ]; do
            RETRY_COUNT=$((RETRY_COUNT+1))
            echo "Push failed, retrying ($RETRY_COUNT/$MAX_RETRIES)..."
            sleep 5
            git pull --rebase origin main
          done

          if [ $RETRY_COUNT -eq $MAX_RETRIES ]; then
            echo "ERROR: Failed to push after $MAX_RETRIES attempts"
            exit 1
          fi

          echo "Successfully pushed changes to main branch"

      - name: Install Helm
        if: steps.update_values.outputs.chart_version_update_needed == 'true'
        uses: azure/setup-helm@v3
        with:
          version: 'latest'

      - name: Package Helm Chart
        if: steps.check_update.outputs.wp_updated == 'true'
        run: |
          helm package .
          echo "Helm chart packaged"

      - name: Create Git Tag
        if: steps.check_update.outputs.wp_updated == 'true'
        run: |
          APP_VERSION="${{ steps.wordpress.outputs.app_version }}"

          # タグが既に存在する場合はスキップ
          if git rev-parse "v$APP_VERSION" >/dev/null 2>&1; then
            echo "Tag v$APP_VERSION already exists, skipping tag creation"
          else
            git tag -a "v$APP_VERSION" -m "Release WordPress $APP_VERSION"
            git push origin "v$APP_VERSION"
            echo "Git tag v$APP_VERSION created"
          fi

      - name: Create Gitea Release
        if: steps.check_update.outputs.wp_updated == 'true'
        env:
          GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
        run: |
          APP_VERSION="${{ steps.wordpress.outputs.app_version }}"
          CHART_NAME=$(grep '^name:' Chart.yaml | awk '{print $2}')
          PACKAGE_FILE="${CHART_NAME}-${APP_VERSION}.tgz"
          RELEASE_BODY="WordPress Helm Chart v${APP_VERSION} - Automated release"

          # リリースが既に存在する場合はスキップ
          if curl -s -H "Authorization: token ${GITEA_TOKEN}" "${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/releases/tags/v${APP_VERSION}" | jq -e '.id' >/dev/null 2>&1; then
            echo "Release v$APP_VERSION already exists, skipping release creation"
          else
            curl -X POST \
              -H "Authorization: token ${GITEA_TOKEN}" \
              -H "Content-Type: application/json" \
              -d "{\"tag_name\":\"v${APP_VERSION}\",\"name\":\"v${APP_VERSION}\",\"body\":\"${RELEASE_BODY}\"}" \
              "${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/releases"

            RELEASE_ID=$(curl -s \
              -H "Authorization: token ${GITEA_TOKEN}" \
              "${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/releases/tags/v${APP_VERSION}" | jq -r '.id')

            curl -X POST \
              -H "Authorization: token ${GITEA_TOKEN}" \
              -H "Content-Type: application/gzip" \
              --data-binary "@${PACKAGE_FILE}" \
              "${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/releases/${RELEASE_ID}/assets?name=${PACKAGE_FILE}"

            echo "Release v${APP_VERSION} created with asset ${PACKAGE_FILE}"
          fi

      - name: Update Helm Repository Index
        if: steps.check_update.outputs.wp_updated == 'true'
        run: |
          set -e
          APP_VERSION="${{ steps.wordpress.outputs.app_version }}"
          CHART_NAME=$(grep '^name:' Chart.yaml | awk '{print $2}')
          PACKAGE_FILE="${CHART_NAME}-${APP_VERSION}.tgz"

          echo "Preparing Helm repository update..."

          # パッケージファイルを一時ディレクトリに移動
          mkdir -p /tmp/helm-repo
          cp "${PACKAGE_FILE}" /tmp/helm-repo/

          # gh-pagesブランチの処理
          if git ls-remote --heads origin gh-pages | grep gh-pages; then
            echo "gh-pages branch exists, checking out..."
            git fetch origin gh-pages
            git checkout gh-pages
          else
            echo "Creating new gh-pages branch..."
            git checkout --orphan gh-pages
            git rm -rf . || true
            echo "# Helm Repository" > README.md
            git config user.name "Gitea Actions Bot"
            git config user.email "actions@git.cafepieters.com"
            git add README.md
            git commit -m "Initialize gh-pages branch"
            git push origin gh-pages
          fi

          # パッケージファイルをコピー
          cp /tmp/helm-repo/"${PACKAGE_FILE}" .

          # index.yamlを生成/更新
          helm repo index . --url "https://git.cafepieters.com/${GITHUB_REPOSITORY}/raw/branch/gh-pages"

          # コミットしてプッシュ
          git config user.name "Gitea Actions Bot"
          git config user.email "actions@git.cafepieters.com"
          git add "${PACKAGE_FILE}" index.yaml
          git commit -m "chore: add ${CHART_NAME} v${APP_VERSION}" || echo "No changes to commit"
          git push origin gh-pages

          echo "Helm repository updated successfully"

          # mainブランチに戻る
          git checkout main

      - name: Summary
        if: always()
        run: |
          APP_VERSION="${{ steps.wordpress.outputs.app_version }}"
          NGINX_VERSION="${{ steps.nginx.outputs.latest }}"
          WP_UPDATED="${{ steps.check_update.outputs.wp_updated }}"

          echo "================================"
          echo "Update completed!"
          echo "- WordPress: ${APP_VERSION}"
          echo "- Nginx: ${NGINX_VERSION}"
          echo ""

          if [ "$WP_UPDATED" = "true" ]; then
            echo "✅ WordPress version updated - Release created (v${APP_VERSION})"
            echo "WordPress updated: ${{ steps.wordpress.outputs.current }} -> ${{ steps.wordpress.outputs.latest }}"
            echo "Nginx updated: ${{ steps.nginx.outputs.current }} -> ${{ steps.nginx.outputs.latest }}"
          elif [ "${{ steps.check_update.outputs.update_needed }}" = "true" ]; then
            echo "ℹ️  Nginx only update - No release (waiting for next WordPress update)"
            echo "Nginx updated: ${{ steps.nginx.outputs.current }} -> ${{ steps.nginx.outputs.latest }}"
          else
            echo "ℹ️  Already up to date - no action required"
          fi
          echo "================================"
