name: Build homebridge-hue-chase
on: 
  workflow_dispatch:
  push:
    branches:
      - master

jobs:
  build:
    name: Build
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 18
      - run: |
          npm ci
          npm run build

  version:
    name: Version
    outputs:
      version: ${{ steps.get_version.outputs.version }}
      commit: ${{ steps.get_version.outputs.commit }}
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 18
      - id: get_version
        name: Set Version
        run: |
          export version=`node -p "require('./package.json').version"`
          export commit=`echo $GITHUB_SHA | cut -c1-5`
          echo "version=$version" >> "$GITHUB_OUTPUT"
          echo "commit=$commit" >> "$GITHUB_OUTPUT"

  publish_tagged:
    name: Publish Latest
    needs: 
      - build
      - version
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
      - run: npm config set @watsonb8:registry https://gitea.watsonlabs.net/api/packages/watsonb8/npm/
      - name: Publish
        env:
          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
          COMMIT: ${{ needs.version.outputs.commit }}
        run: |
          npm config set -- '//gitea.watsonlabs.net/api/packages/watsonb8/npm/:_authToken' "$NPM_TOKEN"
          npm version prerelease --preid="$COMMIT" --git-tag-version=false --allow-same-version=true
          npm publish
  
  deploy:
    runs-on: 
      - ubuntu-latest
      - internal
    name: Deploy
    needs: publish_tagged
    steps:
      - name: Set up SSH key
        run: |
          mkdir -p ~/.ssh
          echo "${{ secrets.ELEVATED_HOMEBRIDGE_SSH_KEY }}" > ~/.ssh/id_rsa
          chmod 600 ~/.ssh/id_rsa
          ssh-keyscan -p 22 homebridge.me >> ~/.ssh/known_hosts
          sudo apt update
          sudo apt install sshpass

      - name: Remove old Package
        run: |
          sshpass -p '${{ secrets.ELEVATED_HOMEBRIDGE_PASSWORD }}' ssh -v -o StrictHostKeyChecking=no ${{ secrets.ELEVATED_HOMEBRIDGE_USER }}@${{ secrets.HOMEBRIDGE_HOST }} <<'ENDSSH'
          rm -r /home/${{ secrets.HOMEBRIDGE_USER }}/.npm-global/lib/node_modules/@watsonb8/homebridge-hue-chase
          ENDSSH
      - name: Deploy
        run: |
          sshpass -p '${{ secrets.ELEVATED_HOMEBRIDGE_PASSWORD }}' ssh -v -o StrictHostKeyChecking=no ${{ secrets.ELEVATED_HOMEBRIDGE_USER }}@${{ secrets.HOMEBRIDGE_HOST }} <<'ENDSSH'
          npm install -g @watsonb8/homebridge-hue-chase
          ENDSSH