name: IACAnsible

on: 
  push:
    branches: [ main ]
  workflow_dispatch:

jobs:
  hello:
    runs-on: fenix-opentofu
    env:
      BW_EMAIL: ${{ secrets.BW_EMAIL }}
      BW_PASSWORD: ${{ secrets.BW_PASSWORD }}
      BW_CLIENTID: ${{ secrets.BW_CLIENTID }}
      BW_CLIENTSECRET: ${{ secrets.BW_CLIENTSECRET }}
      VAULTWARDEN_LINK: ${{secrets.VAULTWARDEN_LINK }}
    steps:
      
      - name: Updating apt-get
        run: |
          apt-get update -y

      - name: Install setup
        run: |
          apt install -y curl jq
          curl -fsSL https://deb.nodesource.com/setup_18.x
          apt-get install -y sshpass

      - name: vaultwarden urls as secrets
        run: |
          echo "config"
          echo "$VAULTWARDEN_LINK"
          bw config server $VAULTWARDEN_LINK
          echo "login"
          bw login --apikey
          echo "session"
          BW_SESSION=$(bw unlock "$BW_PASSWORD" --raw)
          echo "BW_SESSION=$BW_SESSION" >> $GITEA_ENV

      - name: Cloning ansible repository
        uses: actions/checkout@v4
        with:
          path: ansible/iac

      - name: vaultwarden inventory-ini as secrets
        run: |
          BW_SESSION=$(bw unlock "$BW_PASSWORD" --raw)
          echo "getting item"
          bw get item "iac.ansible.hosts.ini"  --session "$BW_SESSION"  | jq -r '.notes' > "inventory.ini"
        working-directory: ansible/iac

      - name: Install Ansible
        run: apt-get install -y ansible

      - name: Run Ansible Playbook
        working-directory: ansible/iac
        run: |
          ansible-playbook -i inventory.ini playbook.yml -e "BW_CLIENTID=$BW_CLIENTID BW_CLIENTSECRET=$BW_CLIENTSECRET BW_PASSWORD=$BW_PASSWORD BW_EMAIL=$BW_EMAIL"
        env:
          BW_SESSION: ${{ env.BW_SESSION }}