name: Build debian packages

on:
  workflow_dispatch:
  push:
    branches:
      - master
      - v*
    paths:
      - ".github/workflows/deb.yml"
      - "release/debian/*"
  pull_request:
    types: [opened, synchronize, reopened]
    paths:
      - ".github/workflows/deb.yml"
      - "release/debian/*"
  release:
    types: [prereleased]

jobs:
  package:
    if: github.repository == 'v2fly/v2ray-core'
    runs-on: ubuntu-latest
    container: golang:1.17-bullseye

    steps:
      - name: Update & install dependencies
        run: |
          apt-get update
          apt-get install -y git wget

      - name: Checkout codebase
        uses: actions/checkout@v2

      - name: Download geo files
        run: |
          wget -O release/config/geoip.dat "https://raw.githubusercontent.com/v2fly/geoip/release/geoip.dat"
          wget -O release/config/geoip-only-cn-private.dat "https://raw.githubusercontent.com/v2fly/geoip/release/geoip-only-cn-private.dat"
          wget -O release/config/geosite.dat "https://raw.githubusercontent.com/v2fly/domain-list-community/release/dlc.dat"

      - name: Install build dependencies
        run: |
          apt-get install -y build-essential dh-golang reprepro

      - name: Build
        run: |
          echo "PATH=${PATH}"
          cp -r release/debian .
          dpkg-buildpackage -us -uc -i -b -d

      - name: Copy binary
        run: |
          cp ../*.deb ./

      - name: Upload artifact
        uses: actions/upload-artifact@v2
        with:
          name: v2ray-debian-packages
          path: ./*.deb

      - name: Setup Repository
        if: ${{ github.event_name == 'release' || github.event_name == 'workflow_dispatch' }}
        run: |
          git clone https://github.com/v2fly/debian.git archive
          echo ${{ secrets.DEBIAN_GPG_PRIVATE }} | base64 -d > private.key
          gpg --import --batch private.key
          gpg -K
          cd archive
          git config --local user.name "${{ github.actor }}"
          git config --local user.email "${{ github.actor }}@users.noreply.github.com"
          git remote set-url origin https://${{ github.actor }}:${{ secrets.DEBIAN_REPO_TOKEN }}@github.com/v2fly/debian.git
          reprepro includedeb stable ../*.deb
          git add -A
          git commit -am 'update'
          git push origin main