name: Build and Deploy

on:
    # Runs on pushes targeting the default branch
    push:
        branches: ["master"]
    release:
        types: [published]

    # Allows you to run this workflow manually from the Actions tab
    workflow_dispatch:

# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
    contents: write
    pages: write
    id-token: write
    packages: write

jobs:
    # deploy docker to github registry
    deployDocker:
        if: github.event_name == 'release' && !github.event.release.prerelease
        runs-on: ubuntu-latest
        env:
            REGISTRY: ghcr.io
            IMAGE_NAME: ${{ github.repository }}
        steps:
            - name: Checkout
              uses: actions/checkout@v4

            - name: Login to GitHub Packages
              uses: docker/login-action@v1
              with:
                  registry: ${{ env.REGISTRY }}
                  username: ${{ github.actor }}
                  password: ${{ secrets.GITHUB_TOKEN }}

            - name: Extract metadata (tags, labels) for Docker
              id: meta
              uses: docker/metadata-action@9ec57ed1fcdbf14dcef7dfbe97b2010124a938b7
              with:
                  images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}

            - name: Build and push Docker image
              uses: docker/build-push-action@f2a1d5e99d037542a71f64918e516c093c6f3fc4
              with:
                  context: .
                  push: true
                  tags: ${{ steps.meta.outputs.tags }}
                  labels: ${{ steps.meta.outputs.labels }}

    deployPackage:
        runs-on: ubuntu-latest
        steps:
            - name: Checkout
              uses: actions/checkout@v4

            - name: Build
              run: |
                  bash build.sh

            # Deploy to GitHub action artifacts
            - name: Upload artifact
              uses: actions/upload-artifact@v4
              with:
                  name: anser-static-snapshot
                  path: "./dist/"

            # Deploy to GitHub Releases
            - name: Compress dist
              if: github.event_name == 'release'
              run: |
                  cd dist
                  zip -r ../anser-static-deploy.zip .
                  cd ..

            - name: Deploy to release branch
              if: github.event_name == 'release'
              run: |
                  # Commit the changes
                  git config --global user.name "Github Actions"
                  git config --global user.email "actions@users.noreply.github.com"

                  git clone --single-branch --branch "releases" https://github.com/${GITHUB_REPOSITORY} releases
                  version="`if [[ $GITHUB_REF == refs\/tags* ]]; then echo ${GITHUB_REF//refs\/tags\//}; fi`"

                  cd releases
                  mkdir -p ${version}
                  mkdir -p latest
                  cp -f ../dist/lib/liquidwallet.lib.js ${version}/liquidwallet.lib.js
                  cp -f ../dist/lib/liquidwallet.lib.js latest/liquidwallet.lib.js

                  git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY

                  git add . || true
                  git commit -m "update ${version}" || true
                  git push origin releases || true

            - name: Deploy to GitHub Releases
              if: github.event_name == 'release'
              run: |
                  set -e
                  echo "${GITHUB_EVENT_PATH}"
                  cat ${GITHUB_EVENT_PATH}
                  releaseId=$(jq --raw-output '.release.id' ${GITHUB_EVENT_PATH})

                  echo "Upload to release $releaseId"

                  filename="./anser-static-deploy.zip"
                  url="https://uploads.github.com/repos/${GITHUB_REPOSITORY}/releases/$releaseId/assets?name=$(basename $filename)"
                  echo "Upload to $url"
                  curl -L \
                  -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
                  -H "Content-Type: application/zip" \
                  --data-binary @"$filename" \
                  "$url"

                  filename="./dist/lib/liquidwallet.lib.js"
                  url="https://uploads.github.com/repos/${GITHUB_REPOSITORY}/releases/$releaseId/assets?name=$(basename $filename)"
                  echo "Upload to $url"
                  curl -L \
                  -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
                  -H "Content-Type: application/javascript" \
                  --data-binary @"$filename" \
                  "$url"

    deployWWW:
        concurrency: ci-${{ github.ref }}
        environment:
            name: github-pages
            url: ${{ steps.deployment.outputs.page_url }}
        runs-on: ubuntu-latest
        steps:
            - name: Checkout
              uses: actions/checkout@v4

            - name: Setup Pages
              if: github.event_name == 'release' && !github.event.release.prerelease
              uses: actions/configure-pages@v4

            - name: Build
              run: |
                  bash build.sh

            - name: Upload artifact
              if: github.event_name == 'release' && !github.event.release.prerelease
              uses: actions/upload-pages-artifact@v3
              with:
                  path: "./dist/"

            - name: Deploy to GitHub Pages
              id: deployment
              if: github.event_name == 'release' && !github.event.release.prerelease
              uses: actions/deploy-pages@v4

            - name: Prepare Node 18
              uses: actions/setup-node@v2
              with:
                  node-version: 18

            - name: Deploy to surge.sh
              uses: dswistowski/surge-sh-action@v1
              with:
                  domain: "anser-snapshot.surge.sh"
                  project: "./dist/"
                  login: ${{ secrets.SURGE_LOGIN }}
                  token: ${{ secrets.SURGE_TOKEN }}

            - name: Upload to ipfs
              if: github.event_name == 'release'
              run: |
                  npm install -g @web3-storage/w3cli
                  mkdir -p /home/runner/.config/w3access
                  echo '${{secrets.W3_ACCESS}}' > ~/.config/w3access/w3cli.json 
                  w3 space use anser
                  w3 up ./dist/ --json > ipfs.json
                  cid=$(jq -r '.root["/"]' ipfs.json)
                  echo "$cid" > deploy.log
                  cat deploy.log

            - name: Write ipfs link to release description
              if: github.event_name == 'release'
              run: |
                  set -e
                  echo "${GITHUB_EVENT_PATH}"
                  cat ${GITHUB_EVENT_PATH}
                  releaseId=$(jq --raw-output '.release.id' ${GITHUB_EVENT_PATH})

                  cid=`cat deploy.log`

                  deployLink="IPfs deployment:\n - ipfs://${cid}\n\nWWW gateway:\n - https://${cid}.ipfs.cf-ipfs.com"
                  echo $deployLink

                  # Add to release description
                  curl -X PATCH \
                  -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
                  -H "Accept: application/vnd.github.v3+json" \
                  https://api.github.com/repos/${GITHUB_REPOSITORY}/releases/$releaseId \
                  -d "{\"body\": \"${deployLink}\"}"
