#
# Copyright (C) 2022 Ing <https://github.com/wjz304>
# 
# This is free software, licensed under the MIT License.
# See /LICENSE for more information.
#

name: Build arpl

on:
  push:
    branches:
      - main
    tags:
      - v*

  release:
    types: [published]

  workflow_dispatch:
    inputs:
      version:
        description: 'format %y.%-m.$i or auto'
        required: false
        type: string

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@main

      # Install dependencies
      - name: Install dependencies
        run: |
          git config --global user.email "github-actions[bot]@users.noreply.github.com"
          git config --global user.name "github-actions[bot]"

          sudo apt update
          sudo apt install -y jq gettext libelf-dev qemu-utils
          sudo snap install yq
          
      # Check dl cache
      - name: Cache downloads
        id: dl-cache
        uses: actions/cache@v3
        with:
          path: ~/dl
          key: ${{ runner.os }}-dl

      # Check buildroot cache
      - name: Cache buildroot
        id: br-cache
        uses: actions/cache@v3
        with:
          path: .buildroot
          key: ${{ runner.os }}-${{ hashFiles('files/configs/arpl_defconfig') }}

      # Clone buildroot repository (if not cached)
      - name: Clone buildroot
        if: steps.br-cache.outputs.cache-hit != 'true'
        run: |
          git clone --single-branch -b 2023.02.x https://github.com/buildroot/buildroot.git .buildroot
          # Copy files
          echo "Copying files"
          cp -Ru files/* .buildroot
          cd .buildroot
          echo "Generating default config"
          make BR2_EXTERNAL=../external arpl_defconfig

      # Download sources if not cached
      - name: Download buildroot packages source
        if: steps.dl-cache.outputs.cache-hit != 'true'
        run: |
          cd .buildroot
          make BR2_EXTERNAL=../external source

      # Prepare buildroot for first make
      - name: Prepare buildroot
        if: steps.br-cache.outputs.cache-hit != 'true'
        run: |
          echo "First make"
          cd .buildroot
          make BR2_EXTERNAL=../external

      # calculates the version number and push
      - name: Calculate version
        run: |
          # Calculate version
          VERSION=""
          if [[ "${{ github.event_name }}" =~ ^(push|release)$ && "${{ github.ref_type }}" == 'tag' ]]; then
            VERSION="${{ github.ref_name }}"
          elif [ -n "${{ inputs.version }}" ]; then
            if [ "`echo ${{ inputs.version }} | cut -d '.' -f 1,2`" = "`date +'%y.%-m'`" ]; then
              VERSION="${{ inputs.version }}"
            else
              LATEST_TAG="`curl -skL "https://api.github.com/repos/${{ github.repository }}/releases/latest" | jq -r ".tag_name" 2>/dev/null`"
              if [ -n "${LATEST_TAG}" -a "`echo ${LATEST_TAG} | cut -d '.' -f 1,2`" = "`date +'%y.%-m'`" ]; then  # format %y.%-m.$i
                VERSION="`echo ${LATEST_TAG} | awk -F '.' '{$3=$3+1}1' OFS='.'`"
              else
                VERSION="`date +'%y.%-m'`.0"
              fi
            fi
          else
            VERSION=""
          fi

          echo "VERSION: ${VERSION}"
          echo "VERSION=${VERSION}" >> $GITHUB_ENV

          if [ -n "${VERSION}" ]; then
            # Modify Source File
            echo "${VERSION}" > VERSION
            echo "${VERSION}" > files/board/arpl/p1/ARPL-VERSION
            sed 's/^ARPL_VERSION=.*/ARPL_VERSION="'${VERSION}'"/' -i files/board/arpl/overlayfs/opt/arpl/include/consts.sh

            git checkout main
            git pull
            status=$(git status -s | awk '{printf " %s", $2}')
            if [ -n "${status}" ]; then
              git add ${status}
              git commit -m "update $(date +%Y-%m-%d" "%H:%M:%S)"
              git push -f
            fi
          fi

      # Convert po2mo, Get extractor, LKM, addons and Modules
      - name: Convert po2mo, Get extractor, LKM, addons and Modules
        run: |
          . scripts/func.sh

          convertpo2mo "files/board/arpl/overlayfs/opt/arpl/lang"
          getExtractor "files/board/arpl/p3/extractor"
          getLKMs "files/board/arpl/p3/lkms"
          getAddons "files/board/arpl/p3/addons"
          getModules "files/board/arpl/p3/modules"

          echo "OK"

      # Build incremental from caches
      - name: Build image
        run: |
          # Remove old files
          rm -rf .buildroot/output/target/opt/arpl
          rm -rf .buildroot/board/arpl/overlayfs
          rm -rf .buildroot/board/arpl/p1
          rm -rf .buildroot/board/arpl/p3

          # Copy files
          echo "Copying files"
          cp -Ru files/* .buildroot/

          cd .buildroot
          echo "Generating default config"
          make BR2_EXTERNAL=../external arpl_defconfig
          echo "Building..."
          make BR2_EXTERNAL=../external
          cd -
          qemu-img convert -O vmdk arpl.img arpl-dyn.vmdk
          qemu-img convert -O vmdk -o adapter_type=lsilogic arpl.img -o subformat=monolithicFlat arpl.vmdk

      # Zip image and generate checksum
      - name: Pack
        run: |
          if [ -n "${{ env.VERSION }}" ]; then
            zip -9 "arpl-i18n-${{ env.VERSION }}.img.zip" arpl.img
            zip -9 "arpl-i18n-${{ env.VERSION }}.vmdk-dyn.zip" arpl-dyn.vmdk
            zip -9 "arpl-i18n-${{ env.VERSION }}.vmdk-flat.zip" arpl.vmdk arpl-flat.vmdk
          else
            zip -9 "arpl-i18n.img.zip" arpl.img
          fi
          sha256sum update-list.yml update-check.sh > sha256sum
          zip -9j update.zip update-list.yml update-check.sh
          while read F; do
            if [ -d "${F}" ]; then
              FTGZ="`basename "${F}"`.tgz"
              tar -czf "${FTGZ}" -C "${F}" .
              sha256sum "${FTGZ}" >> sha256sum
              zip -9j update.zip "${FTGZ}"
              rm "${FTGZ}"
            else
              (cd `dirname ${F}` && sha256sum `basename ${F}`) >> sha256sum
              zip -9j update.zip "${F}"
            fi
          done < <(yq '.replace | explode(.) | to_entries | map([.key])[] | .[]' update-list.yml)
          zip -9j update.zip sha256sum 

      # Upload artifact
      - name: Upload
        uses: actions/upload-artifact@v3
        with:
          name: Images
          path: |
            arpl-i18n.img.zip
            update.zip
          retention-days: 5

      # Publish a release if is a tag
      - name: Release
        uses: softprops/action-gh-release@v1
        if: env.VERSION != ''
        with:
          tag_name: ${{ env.VERSION }}
          files: |
            arpl-i18n-${{ env.VERSION }}.img.zip
            arpl-i18n-${{ env.VERSION }}.vmdk-dyn.zip
            arpl-i18n-${{ env.VERSION }}.vmdk-flat.zip
            update.zip
