name: Deploy Vault

on:
  push:
    branches:
      - master

jobs:
  deploy:
    runs-on: docker

    env:
      # URL of the repository to clone
      TEMPLATE_REPO_URL: https://git.aranroig.com/Syndria98/dnd-vault-template.git
      # Folder name inside the target repo where this repo's contents will be placed
      TARGET_SUBFOLDER: template/vault
      VAULT_NAME: test-campaign

    steps:
      - name: Checkout
        uses: actions/checkout@v3
        with:
          path: current

      - name: Install SSH client
        run: |
          apt-get update -y && apt-get install -y openssh-client

      - name: Setup SSH inside container
        run: |
          mkdir -p ~/.ssh
          echo "${{ secrets.DEPLOY_KEY }}" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/id_ed25519

          # Add the container host to known_hosts
          ssh-keyscan -H ${{ secrets.DEPLOY_HOST }} >> ~/.ssh/known_hosts

      - name: Test SSH
        run: |
          ssh -vvv \
            -o BatchMode=yes \
            deploy@${{ secrets.DEPLOY_HOST }} \
            "echo connected"
      
      - name: Log in to registry
        run: |
          echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login git.aranroig.com -u "${{ secrets.REGISTRY_USER }}" --password-stdin

      - name: Clone target repository
        run: |
          git clone "$TEMPLATE_REPO_URL" target

      - name: Copy current repo contents into target subfolder
        run: |
          rm -Rf target/template/content
          rm -Rf target/$TARGET_SUBFOLDER
          mkdir -p target/$TARGET_SUBFOLDER
          mkdir -p target/template/content
          # Exclude the .git directory from the copy
          rsync -av --exclude={.git,.obsidian,.gitea} current/content/ target/$TARGET_SUBFOLDER/

      - name: Build frontend
        run: |
          docker build -t git.aranroig.com/${{ secrets.REGISTRY_USER }}/vault-$VAULT_NAME:latest ./target/template
          docker push git.aranroig.com/${{ secrets.REGISTRY_USER }}/vault-$VAULT_NAME:latest

      - name: Generate docker compose .env
        run: |
          cat > ./target/.env << EOF
          VAULT_NAME=$VAULT_NAME
          EOF

      - name: Copy files
        run: |
          scp ./target/docker-compose.yml deploy@${{ secrets.DEPLOY_HOST }}:/var/www/app/
          scp ./target/nginx.conf deploy@${{ secrets.DEPLOY_HOST }}:/var/www/app/nginx.conf
          scp ./target/.env deploy@${{ secrets.DEPLOY_HOST }}:/var/www/app/.env

      - name: Deploy
        run: |
          ssh deploy@${{ secrets.DEPLOY_HOST }} << 'EOF'
            echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login git.aranroig.com -u "${{ secrets.REGISTRY_USER }}" --password-stdin
            cd /var/www/app/
            docker compose pull
            docker compose up -d
          EOF
