#!/bin/bash

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

PACKAGES=$(git ls-tree -d --name-only HEAD | grep -v -x -e '.github' -e 'tool')

echo '### Detected following packages:'
for p in $PACKAGES; do
  echo " - $p"
done
read -rp 'Confirm update of labels, issue templates and workflows (y/n):'
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
  echo 'Aborted!'
  exit 1;
fi

create_issue_template() {
  cat <<EOF > "$DIR/../.github/ISSUE_TEMPLATE/$1.md"
---
name: Issue with $1
about: Bug, feature request or question regarding 'package:$1'
title: ''
labels: pkg:$1, pending-triage
assignees:
---
 * Explain the issue,
 * Using bullet points!

\`\`\`dart
// Write example code here
\`\`\`
EOF
}

create_workflow() {
  cat <<EOF > "$DIR/../.github/workflows/pkg-$1.yml"
# Generated by tool/update-github-config.sh
name: $1
on:
  push:
    branches:
      - main
      - master
    paths:
      - '.github/workflows/pkg-$1.yml'
      - '$1/**'
  pull_request:
    paths:
      - '.github/workflows/pkg-$1.yml'
      - '$1/**'
  schedule:
    - cron: "0 0 * * 0"

defaults:
  run:
    working-directory: $1/

env:
  PUB_ENVIRONMENT: bot.github

permissions: read-all

jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        sdk:
         - stable
         - dev
    steps:
    - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
    - uses: dart-lang/setup-dart@e51d8e571e22473a2ddebf0ef8a2123f0ab2c02c
      with:
        sdk: \${{ matrix.sdk }}
    - id: install
      name: Install dependencies
      run: dart pub get
    - name: Check formatting
      run: dart format --output=none --set-exit-if-changed .
      if: always() && steps.install.outcome == 'success'
    - name: Analyze code
      run: dart analyze --fatal-infos
      if: always() && steps.install.outcome == 'success'
    - name: Run tests
      run: dart test
EOF
}

PACKAGE_TABLE='| Package | Description | Version | Test |\n|---|---|---|---|\n'
for P in $PACKAGES; do
  create_issue_template "$P"

  if [[ -f "$DIR/../.github/workflows/pkg-$P-override.yml" ]]; then
    rm -f "$DIR/../.github/workflows/pkg-$P.yml"
    echo "Using pkg-$P-override.yml"
    WF="pkg-$P-override.yml"
  else
    create_workflow "$P"
    WF="pkg-$P.yml"
  fi

  DESCRIPTION=$(python3 -c 'import sys,yaml;print(yaml.safe_load(sys.stdin.read())["description"])' < "$DIR/../$P/pubspec.yaml")
  PACKAGE_TABLE+="| [$P]($P/) | $DESCRIPTION | [![pub package](https://img.shields.io/pub/v/$P.svg)](https://pub.dev/packages/$P) | [![$P](https://github.com/google/dart-neats/actions/workflows/$WF/badge.svg)](https://github.com/google/dart-neats/actions/workflows/$WF) |\n"
done

# Returns 0, if the list $1 contains the element $2.
# Usage: if `list_contains "$MYLIST" "$MYITEM"`; then echo "$MYITEM is here"; fi
function list_contains {
  if [[ $1 =~ (^|[[:space:]])"$2"($|[[:space:]]) ]] ; then
    return 0
  fi
  return 1
}

LABELS=$(gh api -X GET '/repos/google/dart-neats/labels' | jq -r '.[].name' | grep 'pkg:')

for P in $PACKAGES; do
  if list_contains "$LABELS" "pkg:$P"; then 
    echo " - skip pkg:$P"
  else 
    echo " - creating: pkg:$P"
    gh api -X POST '/repos/google/dart-neats/labels' -F name="pkg:$P" -F color=f29513 | jq
  fi
done


awk -i inplace -v package_table="$PACKAGE_TABLE" '
{
  if ($0 ~ /BEGIN PACKAGE TABLE/) {
    print
    print package_table
    skip_lines=1
    next
  }
  if ($0 ~ /END PACKAGE TABLE/) {
    print
    skip_lines=0
    next
  }
  if (!skip_lines) {
    print
  }
}
' "$DIR/../README.md"
