name: Build for Linux x64

on:
  workflow_call:
    inputs:
      tag:
        description: "tag"
        required: false
        default: ""
        type: string
  workflow_dispatch:

jobs:
  build-linux-app:
    name: Release Linux x64
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Install dependencies
        run: |
          sudo apt-get update
          sudo apt-get install -y clang cmake libgtk-3-dev ninja-build libayatana-appindicator3-dev unzip webkit2gtk-4.1 libasound2-dev rpm patchelf
          sudo apt-get install -y gcc g++ autoconf automake debhelper glslang-dev ladspa-sdk xutils-dev libasound2-dev \
              libarchive-dev libbluray-dev libbs2b-dev libcaca-dev libcdio-paranoia-dev libdrm-dev \
              libdav1d-dev libdvdnav-dev libegl1-mesa-dev libepoxy-dev libfontconfig-dev libfreetype6-dev \
              libfribidi-dev libgl1-mesa-dev libgbm-dev libgme-dev libgsm1-dev libharfbuzz-dev libjpeg-dev \
              libbrotli-dev liblcms2-dev libmodplug-dev libmp3lame-dev libopenal-dev \
              libopus-dev libopencore-amrnb-dev libopencore-amrwb-dev libpulse-dev librtmp-dev \
              libsdl2-dev libsixel-dev libssh-dev libsoxr-dev libspeex-dev libtool \
              libv4l-dev libva-dev libvdpau-dev libvorbis-dev libvo-amrwbenc-dev \
              libunwind-dev libvpx-dev libwayland-dev libx11-dev libxext-dev \
              libxkbcommon-dev libxrandr-dev libxss-dev libxv-dev libxvidcore-dev \
              linux-libc-dev nasm ninja-build pkg-config python3 python3-docutils wayland-protocols \
              x11proto-core-dev zlib1g-dev libfdk-aac-dev libtheora-dev libwebp-dev \
              unixodbc-dev libpq-dev libxxhash-dev libaom-dev \
              libgtk-3-0 libblkid1 liblzma5 libmpv-dev
        shell: bash

      - name: Setup flutter
        uses: subosito/flutter-action@v2
        with:
          channel: stable
          flutter-version-file: pubspec.yaml
          cache: true

      - name: Set and Extract version
        shell: pwsh
        run: lib/scripts/build.ps1

      - name: Apply Patch
        shell: pwsh
        run: lib/scripts/patch.ps1 Linux
        continue-on-error: true

        #TODO: deb and rpm packages need to be build
      - name: Build Linux
        run: flutter build linux --release -v --pub --dart-define-from-file=pili_release.json

      - name: Package .tar.gz
        run: tar -zcvf PiliPlus_linux_${{ env.version }}_amd64.tar.gz -C build/linux/x64/release/bundle .

      - name: Packege deb
        run: |
          printf "建立构建目录...\n"
          mkdir "PiliPlus_linux_${{ env.version }}_amd64"
          pushd "PiliPlus_linux_${{ env.version }}_amd64"
          mkdir -p opt/PiliPlus
          mkdir -p usr/share/applications
          mkdir -p usr/share/icons/hicolor/512x512/apps

          printf "复制文件...\n"
          cp -r ../build/linux/x64/release/bundle/* opt/PiliPlus
          cp -r ../assets/linux/DEBIAN .
          cp ../assets/linux/com.example.piliplus.desktop usr/share/applications
          cp ../assets/images/logo/logo.png usr/share/icons/hicolor/512x512/apps/piliplus.png

          printf "修改控制文件...\n"
          # 替换版本号
          sed -i  "2s/version_need_change/${{ env.version }}/g" DEBIAN/control
          # 计算安装大小并替换
          SIZE_KB=$(du -s -b --apparent-size . | awk '{print int($1)}')
          SIZE_KB=$(($SIZE_KB - $(du -s -b --apparent-size DEBIAN | awk '{print int($1)}')))
          SIZE_KB=$(echo $SIZE_KB | awk '{print int($1/1024 + 0.999)}')
          printf "\t安装大小: %s KB\n" "$SIZE_KB"
          sed -i "9s/size_need_change/${SIZE_KB}/g" DEBIAN/control

          printf "生成并写入 md5sums ...\n"
          md5sum opt/PiliPlus/piliplus >> DEBIAN/md5sums
          md5sum opt/PiliPlus/lib/* >> DEBIAN/md5sums
          md5sum opt/PiliPlus/data/icudtl.dat >> DEBIAN/md5sums

          printf "设置权限...\n"
          chmod 0644 DEBIAN/control
          chmod 0644 DEBIAN/md5sums
          chmod 0755 DEBIAN/postinst
          chmod 0755 DEBIAN/postrm
          chmod 0755 DEBIAN/prerm

          printf "打包 deb 文件...\n"
          popd
          dpkg-deb --build --verbose --root-owner-group "PiliPlus_linux_${{ env.version }}_amd64"
          printf "完成: PiliPlus_linux_%s_amd64.deb\n" "${{ env.version }}"
        shell: bash

      - name: Packege rpm
        run: |
          printf "建立 RPM 构建目录...\n"
          RPM_BUILD_ROOT="$PWD/rpm_build"
          mkdir -p "$RPM_BUILD_ROOT/BUILD" "$RPM_BUILD_ROOT/RPMS" "$RPM_BUILD_ROOT/SOURCES" "$RPM_BUILD_ROOT/SPECS" "$RPM_BUILD_ROOT/SRPMS"

          printf "准备源码归档（仅包含运行时与元数据）...\n"
          DATE="$(date '+%a %b %d %Y')"
          SRC_DIR="$PWD/piliplus-${{ env.version }}"
          mkdir -p "$SRC_DIR/bundle" "$SRC_DIR/assets"
          cp -r build/linux/x64/release/bundle/* "$SRC_DIR/bundle/"
          cp assets/linux/com.example.piliplus.desktop "$SRC_DIR/assets/com.example.piliplus.desktop"
          cp assets/images/logo/logo.png "$SRC_DIR/assets/piliplus.png"
          tar -zcvf "$RPM_BUILD_ROOT/SOURCES/piliplus-${{ env.version }}.tar.gz" -C "$PWD" "piliplus-${{ env.version }}"

          printf "生成 spec 文件...\n"
          cat > "$RPM_BUILD_ROOT/SPECS/piliplus.spec" <<EOF
          Name:           piliplus
          Version:        ${{ env.version }}
          Release:        1%{?dist}
          Summary:        PiliPlus Linux Version
          License:        GPL-3.0
          Source0:        piliplus-${{ env.version }}.tar.gz
          Requires:       desktop-file-utils, hicolor-icon-theme

          %description
          使用 Flutter 开发的 BiliBili 第三方客户端

          %prep
          %setup -q -n piliplus-${{ env.version }}

          %build

          %install
          mkdir -p %{buildroot}/opt/PiliPlus
          cp -r bundle/* %{buildroot}/opt/PiliPlus/

          # 二进制权限与命令行入口
          chmod 755 %{buildroot}/opt/PiliPlus/piliplus
          mkdir -p %{buildroot}/usr/bin
          ln -sf /opt/PiliPlus/piliplus %{buildroot}/usr/bin/piliplus

          # 桌面集成
          mkdir -p %{buildroot}/usr/share/applications
          install -m 644 assets/com.example.piliplus.desktop %{buildroot}/usr/share/applications/com.example.piliplus.desktop

          mkdir -p %{buildroot}/usr/share/icons/hicolor/512x512/apps
          install -m 644 assets/piliplus.png %{buildroot}/usr/share/icons/hicolor/512x512/apps/piliplus.png

          %post
          update-desktop-database -q || true
          gtk-update-icon-cache -q -t -f %{_datadir}/icons/hicolor || true

          %postun
          update-desktop-database -q || true
          gtk-update-icon-cache -q -t -f %{_datadir}/icons/hicolor || true

          %files
          /opt/PiliPlus
          /usr/bin/piliplus
          /usr/share/applications/com.example.piliplus.desktop
          /usr/share/icons/hicolor/512x512/apps/piliplus.png

          %changelog
          * DATE - ${{ env.version }}-1
          - Initial RPM release
          EOF

          sed -i "s/DATE/${DATE}/g" "$RPM_BUILD_ROOT/SPECS/piliplus.spec"

          printf "构建 RPM 包...\n"
          rpmbuild --define "_topdir $RPM_BUILD_ROOT" -bb "$RPM_BUILD_ROOT/SPECS/piliplus.spec"

          printf "移动生成的 RPM...\n"
          find "$RPM_BUILD_ROOT/RPMS" -name "*.rpm" -exec mv {} "PiliPlus_linux_${{ env.version }}_amd64.rpm" \;

          printf "完成: PiliPlus_linux_%s_amd64.rpm\n" "${{ env.version }}"
        shell: bash

      - name: Package AppImage
        run: |
          printf "下载 appimagetool...\n"
          wget -q https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-x86_64.AppImage
          chmod +x appimagetool-x86_64.AppImage

          printf "建立 AppDir 目录结构...\n"
          APPDIR="PiliPlus.AppDir"
          mkdir -p "$APPDIR/usr/bin"
          mkdir -p "$APPDIR/usr/lib"
          mkdir -p "$APPDIR/usr/share/applications"
          mkdir -p "$APPDIR/usr/share/icons/hicolor/512x512/apps"

          printf "复制应用文件...\n"
          cp -r build/linux/x64/release/bundle/* "$APPDIR/usr/bin/"

          printf "复制桌面文件和图标...\n"
          cp assets/linux/com.example.piliplus.desktop "$APPDIR/com.example.piliplus.desktop"
          cp assets/linux/com.example.piliplus.desktop "$APPDIR/usr/share/applications/com.example.piliplus.desktop"
          cp assets/images/logo/logo.png "$APPDIR/piliplus.png"
          cp assets/images/logo/logo.png "$APPDIR/usr/share/icons/hicolor/512x512/apps/piliplus.png"

          printf "创建 AppRun 启动脚本...\n"
          cat > "$APPDIR/AppRun" <<'APPRUN_EOF'
          #!/bin/bash
          SELF=$(readlink -f "$0")
          HERE=${SELF%/*}
          export PATH="${HERE}/usr/bin:${PATH}"
          export LD_LIBRARY_PATH="${HERE}/usr/lib:${LD_LIBRARY_PATH}"
          exec "${HERE}/usr/bin/piliplus" "$@"
          APPRUN_EOF
          chmod +x "$APPDIR/AppRun"

          printf "修改桌面文件中的 Exec 路径...\n"
          sed -i 's|Exec=piliplus|Exec=piliplus|g' "$APPDIR/com.example.piliplus.desktop"
          sed -i 's|Icon=piliplus|Icon=piliplus|g' "$APPDIR/com.example.piliplus.desktop"

          printf "打包 AppImage...\n"
          ARCH=x86_64 ./appimagetool-x86_64.AppImage "$APPDIR" "PiliPlus_linux_${{ env.version }}_amd64.AppImage"

          printf "完成: PiliPlus_linux_%s_amd64.AppImage\n" "${{ env.version }}"
        shell: bash

      - name: Release
        if: ${{ github.event.inputs.tag != '' }}
        uses: softprops/action-gh-release@v2
        with:
          tag_name: ${{ github.event.inputs.tag }}
          name: ${{ github.event.inputs.tag }}
          files: |
            PiliPlus_linux_*.tar.gz
            PiliPlus_linux_*.deb
            PiliPlus_linux_*.rpm
            PiliPlus_linux_*.AppImage

      - name: Upload linux targz package
        uses: actions/upload-artifact@v7
        with:
          archive: false
          name: Linux_targz_amd64_packege
          path: PiliPlus_linux_*.tar.gz

      - name: Upload linux deb package
        uses: actions/upload-artifact@v7
        with:
          archive: false
          name: Linux_deb_amd64_package
          path: PiliPlus_linux_*.deb

      - name: Upload linux rpm package
        uses: actions/upload-artifact@v7
        with:
          archive: false
          name: Linux_rpm_amd64_package
          path: PiliPlus_linux_*.rpm

      - name: Upload linux AppImage package
        uses: actions/upload-artifact@v7
        with:
          archive: false
          name: Linux_AppImage_amd64_package
          path: PiliPlus_linux_*.AppImage
