name: "ci"

on:
  push:
    tags: "**"
  workflow_dispatch:

defaults:
  run:
    shell: bash

jobs:
  appimage:
    runs-on: ubuntu-18.04

    steps:
    - name: Checkout repository
      uses: actions/checkout@v2
      with:
        submodules: true

    - name: Install dependencies
      run: |
        sudo add-apt-repository -y ppa:beineri/opt-qt-5.15.2-bionic
        sudo apt-get update -qq
        sudo apt-get install -y \
        build-essential make wget libgl1-mesa-dev \
        qt515declarative qt515graphicaleffects \
        qt515quickcontrols qt515quickcontrols2

    - name: Download QT appimage builder
      run: |
        wget -c -O linuxdeployqt.AppImage \
        https://github.com/probonopd/linuxdeployqt/releases/download/continuous/linuxdeployqt-continuous-x86_64.AppImage
        chmod a+x linuxdeployqt.AppImage

    - name: Build project
      run: |
        source /opt/qt*/bin/qt*-env.sh && \
        qmake -v && \
        qmake CONFIG+=release PREFIX=/usr && \
        make -j$(nproc)

    - name: Install to appdir
      run: |
        source /opt/qt*/bin/qt*-env.sh && \
        make INSTALL_ROOT=appdir -j$(nproc) install

    - name: Extract version number
      run: |
        # Extract version for linuxdeployqt to name the file. Use the tag as
        # release name but remove prefix.
        echo "VERSION=$(echo '${{ github.ref }}' | sed 's;.*/;;')" >> $GITHUB_ENV

    - name: Build appimage directory
      run: |
        mkdir -p \
        appdir/usr/bin \
        appdir/usr/lib \
        appdir/usr/share/applications \
        appdir/usr/share/metainfo \
        appdir/usr/share/icons/hicolor/128x128/apps

        cp cool-retro-term appdir/usr/bin/
        cp cool-retro-term.desktop appdir/usr/share/applications/
        cp packaging/appdata/cool-retro-term.appdata.xml appdir/usr/share/metainfo/
        cp app/icons/128x128/cool-retro-term.png appdir/usr/share/icons/hicolor/128x128/apps/
        cp -r ./app/qml appdir/usr/
        # Workaround for https://github.com/probonopd/linuxdeployqt/issues/78
        cp -r ./qmltermwidget/QMLTermWidget appdir/usr/qml/

        find appdir | sort

    - name: Build appimage
      run: |
        source /opt/qt*/bin/qt*-env.sh && \
        ./linuxdeployqt.AppImage appdir/usr/share/applications/cool-retro-term.desktop \
        -verbose=1 -appimage \
        -qmldir=./app/qml/ \
        -qmldir=./qmltermwidget/
      env:
        # Unset environment variables
        QTDIR:
        QT_PLUGIN_PATH:
        LD_LIBRARY_PATH:

    - name: Upload release
      uses: softprops/action-gh-release@v1
      with:
        body: appimage release
        files: ./**/Cool_Retro_Term-*-x86_64.AppImage

    - name: Clean up
      if: always()
      run: |
        find appdir -executable -type f -exec ldd {} \; | grep " => /usr" | cut -d " " -f 2-3 | sort | uniq
        make clean
        rm -rf appdir
