name: Build packages
on: [push]

permissions:
  contents: write
  packages: write
jobs:
  check-launchpad:
    runs-on: ubuntu-latest
    outputs:
      launchpad_accessible: ${{ steps.check.outputs.accessible }}
    steps:
      - name: Check if launchpad.net is accessible
        id: check
        run: |
          # Try to access launchpad.net (timeout after 5 seconds)
          if curl -s --max-time 5 https://launchpad.net > /dev/null; then
            echo "accessible=true" >> $GITHUB_OUTPUT
          else
            echo "accessible=false" >> $GITHUB_OUTPUT
          fi
  build:
    runs-on: ubuntu-latest
    needs: check-launchpad
    if: needs.check-launchpad.outputs.launchpad_accessible == 'true'
    steps:
      - name: Checkout code
        uses: actions/checkout@v3
        with:
          path: "REPO"

      - name: Define variables
        run: |
          (
            VERSION=$(echo "${GITHUB_REF_NAME}" | sed -e 's/^v//')
            if ! [[ $VERSION =~ ^[0-9] ]]; then
              VERSION="$(sed -n 's/^version[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p' REPO/pyproject.toml || true)+${{github.sha}}"
            fi
            echo "GITHUB_REPO_NAME=$(echo "${GITHUB_REPOSITORY}" | cut -d/ -f2)"
            echo "VERSION=${VERSION}"
            echo "DEB_ARCHITECTURE=${ARCHITECTURE:-all}"
            echo "RPM_ARCHITECTURE=${ARCHITECTURE:-noarch}"
            echo "RELEASE=1"
            echo "AUTHOR=Jeffrey Ratcliffe <jffry@posteo.net>"
            cd REPO
            echo "FIRST_YEAR=$(git log $(git rev-list --max-parents=0 HEAD) --date="format:%Y" --format="format:%ad")"
            echo "THIS_COMMIT_YEAR=$(git log HEAD -n1 --date="format:%Y" --format="format:%ad")"
            echo "THIS_COMMIT_DATE=$(git log HEAD -n1 --format="format:%as")"
            if [ "$FIRST_YEAR" == "$THIS_COMMIT_YEAR" ]
            then
              echo "YEAR_RANGE=$FIRST_YEAR"
            else
              echo "YEAR_RANGE=${FIRST_YEAR}-${THIS_COMMIT_YEAR}"
            fi
            cd ..
          ) >> $GITHUB_ENV

      - name: Create control files
        # Fields from https://www.debian.org/doc/debian-policy/ch-controlfields.html#binary-package-control-files-debian-control
        run: |
          mkdir -p REPO/debian/upstream
          mkdir -p REPO/debian/source
          echo "3.0 (quilt)" | tee REPO/debian/source/format
          (
            echo "Source: ${GITHUB_REPO_NAME}"
            echo "Section: utils"
            echo "Testsuite: autopkgtest-pkg-python"
            echo "Build-Depends: debhelper-compat (= 13),"
            echo "               dh-python,"
            echo "               python3-all,"
            echo "               python3-pip,"
            echo "               python3-setuptools,"
            echo "               python3-wheel"
            echo "Build-Depends-Indep: fonts-noto-extra,"
            echo "                     gettext,"
            echo "                     ghostscript,"
            echo "                     gir1.2-gtk-3.0,"
            echo "                     gir1.2-goocanvas-2.0,"
            echo "                     gsfonts,"
            echo "                     help2man,"
            echo "                     imagemagick,"
            echo "                     librsvg2-common,"
            echo "                     libtiff-tools,"
            echo "                     ocrmypdf (>= 15.4.3),"
            echo "                     pandoc,"
            echo "                     pybuild-plugin-pyproject,"
            echo "                     python3-gi,"
            echo "                     python3-gi-cairo,"
            echo "                     python3-iso639,"
            echo "                     python3-sane,"
            echo "                     python3-tesserocr,"
            echo "                     python3-polib,"
            echo "                     python3-pytest-cov,"
            echo "                     python3-pytest-timeout,"
            echo "                     python3-pytest-pylint,"
            echo "                     python3-pytest-mock,"
            echo "                     python3-pytest-xvfb,"
            echo "                     sane-utils (>= 1.0.17),"
            echo "                     xauth,"
            echo "                     xfonts-base"
            echo "Maintainer: ${AUTHOR}"
            echo "Standards-Version: 4.7.3"
            echo "Vcs-Git: https://github.com/carygravel/scantpaper.git"
            echo "Vcs-Browser: https://github.com/carygravel/scantpaper"
            echo "Homepage: https://github.com/carygravel/scantpaper"
            echo ""
            echo "Package: ${GITHUB_REPO_NAME}"
            echo "Architecture: ${DEB_ARCHITECTURE}"
            echo "Depends: gir1.2-gtk-3.0,"
            echo "         gir1.2-goocanvas-2.0,"
            echo "         imagemagick,"
            echo "         librsvg2-common,"
            echo "         libtiff-tools,"
            echo "         ocrmypdf (>= 15.4.3),"
            echo "         poppler-utils,"
            echo "         python3-gi,"
            echo "         python3-gi-cairo,"
            echo "         python3-iso639,"
            echo "         python3-sane,"
            echo "         python3-tesserocr,"
            echo "         sane-utils (>= 1.0.17),"
            echo "         \${misc:Depends},"
            echo "         \${python3:Depends}"
            echo "Recommends: djvulibre-bin,"
            echo "            qpdf,"
            echo "            tesseract-ocr,"
            echo "            unpaper,"
            echo "            xdg-utils"
            echo "Description: GUI to produce PDFs or DjVus from scanned documents"
            echo " Only five clicks are required to scan several pages and then save all or"
            echo " a selection as a PDF or DjVu file, including metadata if required."
            echo " ."
            echo " scantpaper can control flatbed or sheet-fed (ADF) scanners with SANE,"
            echo " and can scan multiple pages at once. It presents a thumbnail view of"
            echo " scanned pages, and permits simple operations such as cropping, rotating"
            echo " and deleting pages."
            echo " ."
            echo " OCR can be used to recognise text in the scans, and the output"
            echo " embedded in the PDF or DjVu."
            echo " ."
            echo " The resulting document may be saved as a PDF, DjVu, multipage TIFF file, or"
            echo " single page image file."
            echo " ."
            echo " PDF conversion is done by ocrmypdf."
            if [ -n "${HOMEPAGE}" ]
            then
              echo "Homepage: ${HOMEPAGE}"
            fi
          ) | tee REPO/debian/control
          (
            echo "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/"
            echo "Upstream-Name: scantpaper"
            echo "Upstream-Contact: Jeffrey Ratcliffe <jffry@posteo.net>"
            echo "Source: https://github.com/carygravel/scantpaper"
            echo ""
            echo "Files: *"
            echo "Copyright: 2006--2026 Jeffrey Ratcliffe"
            echo "License: GPL-3"
            echo " The full text of the GPL is available on Debian systems in"
            echo " /usr/share/common-licenses/GPL-3"
            echo ""
            echo "Files: scantpaper.appdata.xml"
            echo "Copyright: 2006--2026 Jeffrey Ratcliffe"
            echo "License: CC0-1.0"
            echo " The full text of the CC0-1.0 licence is available on Debian systems in"
            echo " /usr/share/common-licenses/CC0-1.0"
            echo ""
            echo "Files: icons/hicolor/scalable/apps/scan.svg"
            echo "Copyright: 2007 Frédéric Bellaiche"
            echo "License: GPL"
            echo " The full text of the GPL is available on Debian systems in"
            echo " /usr/share/common-licenses/GPL"
            echo ""
            echo "Files: icons/hicolor/scalable/apps/pdf.svg"
            echo "Copyright: 2004 David Vignoni"
            echo "License: LGPL-2.1"
            echo " The full text of the GPL is available on Debian systems in"
            echo " /usr/share/common-licenses/LGPL-2.1"
          ) | tee REPO/debian/copyright
          (
            echo "${GITHUB_REPO_NAME} (${VERSION}-0) unstable; urgency=medium"
            echo ""
            echo "  * New upstream release candidate"
            echo ""
            echo " -- ${AUTHOR}  $(date --rfc-email)"
            echo ""
          ) | tee REPO/debian/changelog
          (
            echo "#!/usr/bin/make -f"
            echo ""
            echo "export DH_VERBOSE=1"
            echo "export PIP_NO_CACHE_DIR=1"
            echo "export XDG_CACHE_HOME=\$(CURDIR)/.cache"
            echo ""
            echo "include /usr/share/dpkg/pkg-info.mk"
            echo "export DEB_VERSION_UPSTREAM"
            echo ""
            echo "%:"
            echo "	dh \$@ --with python3 --buildsystem=pybuild"
            echo ""
            echo "override_dh_auto_build:"
            echo "	dh_auto_build"
            echo "	python3 dev/compile_mo.py --src po --out debian/locale --domain scantpaper"
            echo "	pandoc README.md -o debian/documentation.html"
            echo ""
            echo "override_dh_installdocs:"
            echo "	dh_installdocs README.md debian/documentation.html"
            echo ""
            echo "override_dh_install:"
            echo "	dh_install"
            echo ""
            echo "	# install locale manually into package staging area"
            echo "	mkdir -p debian/scantpaper/usr/share/locale"
            echo "	cp -a debian/locale/. debian/scantpaper/usr/share/locale/"
            echo ""
            echo "override_dh_installman:"
            echo "	help2man --no-info --name='a GUI to produce PDFs or DjVus from scanned documents' --version-string=\$(DEB_VERSION_UPSTREAM) --output=\$(CURDIR)/debian/scantpaper.1 'python3 scantpaper/app.py'"
            echo "	sed -i -e 's/APP.PY/SCANTPAPER/' -e 's/app.py/scantpaper/' \$(CURDIR)/debian/scantpaper.1"
            echo "	dh_installman"
            echo ""
            echo "override_dh_auto_test: ;"
          ) | tee REPO/debian/rules
          echo "debian/scantpaper.1" | tee REPO/debian/scantpaper.manpages
          (
            echo "debian/documentation.html usr/share/doc/scantpaper/"
            echo "icons/* usr/share/icons/"
            echo "org.scantpaper.desktop usr/share/applications"
            echo "scantpaper.appdata.xml usr/share/metainfo"
          ) | tee REPO/debian/scantpaper.install
          (
            echo "Bug-Database: https://github.com/carygravel/scantpaper/issues"
            echo "Bug-Submit: https://github.com/carygravel/scantpaper/issues/new"
            echo "Changelog: https://github.com/carygravel/scantpaper/blob/main/changelog.md"
            echo "Repository-Browse: https://github.com/carygravel/scantpaper"
            echo "Repository: https://github.com/carygravel/scantpaper"
          ) | tee REPO/debian/upstream/metadata
          (
            echo "Version: 5"
            echo ""
            echo "Template: Github"
            echo "Owner: carygravel"
            echo "Project: @PACKAGE@"
          ) | tee REPO/debian/watch

      - name: Install dependencies
        run: |
          sudo add-apt-repository ppa:jeffreyratcliffe/ppa
          sudo apt-get update
          sudo apt-get install -y build-essential debhelper devscripts fakeroot lintian equivs
          sudo mk-build-deps --install --remove REPO/debian/control # Install build dependencies from debian/control

      - name: Build DEB Package
        run: cd REPO && debuild -i -us -uc -b && dpkg-deb --contents ../${{ env.GITHUB_REPO_NAME }}_${{ env.VERSION }}-0_all.deb

      - name: Upload packages
        run: ls -l
      - uses: actions/upload-artifact@v4
        with:
          name: ${{ env.GITHUB_REPO_NAME }}_${{ env.VERSION }}-0_all.deb
          path: ${{ env.GITHUB_REPO_NAME }}_${{ env.VERSION }}-0_*

      - name: Release packages
        uses: softprops/action-gh-release@v2
        if: github.ref_type == 'tag'
        with:
          files: |
            ${{ env.GITHUB_REPO_NAME }}_${{ env.VERSION }}-0_all.deb
