name: Push to Azure VM

on:
  workflow_dispatch:
    inputs:
      hostname:
        description: 'Hostname where the webapp should be reachable'
        type: string
        required: true
        default: 'lyprox.org'
      port:
        description: 'Port to use on the hosting VM'
        type: number
        required: true
        default: 8000
      pyver:
        description: 'Python version to use'
        type: string
        required: true
        default: '3.10'

  push:
    tags: [ '*' ]

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
    - name: Set variables for workflow_dispatch event
      if: github.event_name == 'workflow_dispatch'
      run: |
        echo "PYVER=${{ github.event.inputs.pyver }}" >> $GITHUB_ENV
        echo "HOSTNAME=${{ github.event.inputs.hostname }}" >> $GITHUB_ENV
        echo "PORT=${{ github.event.inputs.port }}" >> $GITHUB_ENV

    - name: Set variables for push event
      if: github.event_name == 'push'
      run: |
        echo "PYVER=3.10" >> $GITHUB_ENV
        echo "HOSTNAME=lyprox.org" >> $GITHUB_ENV
        echo "PORT=8000" >> $GITHUB_ENV

    - name: SSH Remote Commands
      uses: appleboy/ssh-action@v1.0.0
      with:
        host: ${{ secrets.REMOTE_IP }}
        username: ${{ secrets.REMOTE_USERNAME }}
        key: ${{ secrets.REMOTE_KEY }}
        port: 22
        script: |
          TMPFILE=$(mktemp)
          wget https://raw.githubusercontent.com/rmnldwg/lyprox/${{ github.ref_name }}/setup.sh -O $TMPFILE
          sudo bash $TMPFILE -p ${{ env.PYVER }} -b ${{ github.ref_name }} ${{ env.HOSTNAME }} ${{ env.PORT }}
          sudo echo 'DJANGO_SECRET_KEY="${{ secrets.DJANGO_SECRET_KEY }}"' >> /srv/www/${{ env.HOSTNAME }}/.env
          sudo echo 'GITHUB_TOKEN="${{ secrets.READONLY_TOKEN }}"' >> /srv/www/${{ env.HOSTNAME }}/.env
          sudo echo '${{ secrets.DJANGO_PASSWORDS }}' >> /srv/www/${{ env.HOSTNAME }}/.env
          sudo systemctl restart ${{ env.HOSTNAME }}.service
