---
version: '3'

vars:
  COMMON_FOLDER: .common
  DOCS_URL: https://gitlab.com/megabyte-labs/documentation/{{.REPOSITORY_SUBTYPE}}
  SHARED_COMMON_URL: https://gitlab.com/megabyte-labs/common/shared.git
  SHARED_FOLDER: .shared

tasks:
  clean:
    log:
      error: Error running `rm -rf {{.SHARED_FOLDER}}`
      start: Running `rm -rf {{.SHARED_FOLDER}}`
      success: Removed `{{.SHARED_FOLDER}}`
    cmds:
      - rm -rf {{.SHARED_FOLDER}}
      - rm -f .config/docs/Taskfile.yml

  clone:
    cmds:
      - task: clone:common
      - task: clone:docs

  clone:common:
    log:
      error: Error cloning Shared Common to `{{.SHARED_FOLDER}}`
      start: Cloning Shared Common to `{{.SHARED_FOLDER}}`
      success: Cloned Shared Common to `{{.SHARED_FOLDER}}`
    cmds:
      - rm -rf ./{{.SHARED_FOLDER}}
      - git clone --depth=1 {{.SHARED_COMMON_URL}} ./{{.SHARED_FOLDER}}
      - rm -rf ./{{.SHARED_FOLDER}}/.git

  clone:docs:
    log:
      error: Error cloning / cleaning up {{.REPOSITORY_SUBTYPE}} docs repo
      start: Cloning {{.REPOSITORY_SUBTYPE}} docs repo and pruning unnecessary files
      success: Cloned sub-type documentation repository and pruned unnecessary files
    cmds:
      - mkdir -p ./{{.SHARED_FOLDER}}/common/.config
      - rm -rf ./{{.SHARED_FOLDER}}/.config/docs
      - git clone --depth=1 {{.DOCS_URL}} ./{{.SHARED_FOLDER}}/common/.config/docs
      - |
        cd ./{{.SHARED_FOLDER}}/common/.config/docs
        rm -rf .git .config .github .gitlab .vscode .editorconfig .gitignore .gitlab-ci.yml
        rm -rf LICENSE Taskfile.yml package-lock.json package.json poetry.lock pyproject.toml
        rm -rf docs common.json pnpm-lock.yaml start.sh logo.png yarn.lock local/yarn.lock local/package-lock.json
        rm -rf .devcontainer local/slim

  combine:
    log:
      error: Error combining generated files
      start: Combining generated files
      success: Combined generated files
    cmds:
      - mkdir -p _generated_
      - mv .common* _generated_
      - |
        mv _generated_/.common _generated_/common
        for FOLDER in _generated_/.common-*; do
          TARGET="$(echo $FOLDER | sed 's/^_generated_\/.common-//')"
          mv "$FOLDER" "_generated_/$TARGET"
        done

  copy:
    deps:
      - :install:software:yq
    log:
      error: Error removing `.config/`
      start: Removing `.config/`
      success: Removed `.config/`
    cmds:
      - mv .gitlab-ci.yml old.gitlab-ci.yml
      - task: copy:begin
      - |
        yq eval-all -i 'select(fileIndex == 0) * select(fileIndex == 1)' old.gitlab-ci.yml .gitlab-ci.yml
        mv old.gitlab-ci.yml .gitlab-ci.yml

  copy:begin:
    deps:
      - copy:common
      - copy:project
      - copy:project:subtype

  copy:common:
    deps:
      - :install:software:coreutils
    log:
      error: Error copying common files
      start: Copying common files
      success: Copied common files
    cmds:
      - |
        {{if (eq OS "darwin")}}PATH="$(brew --prefix)/opt/coreutils/libexec/gnubin:$PATH"{{end}}
        cp -rT ./{{.SHARED_FOLDER}}/common/ .
      - task: :common:husky:permissions

  copy:project:
    deps:
      - :install:software:coreutils
    log:
      error: Error copying project files
      start: Copying project files
      success: Copied project files
    cmds:
      - |
        {{if (eq OS "darwin")}}PATH="$(brew --prefix)/opt/coreutils/libexec/gnubin:$PATH"{{end}}
        cp -rT ./{{.SHARED_FOLDER}}/common ./{{.COMMON_FOLDER}}
        if [ ! -d project ]; then mkdir project; fi
        cp -rT project ./{{.COMMON_FOLDER}}

  copy:project:subtype:
    deps:
      - :install:software:coreutils
    log:
      error: Error copying project sub-type files
      start: Copying project sub-type files
      success: Copied project sub-type files
    cmds:
      - |
        {{if (eq OS "darwin")}}PATH="$(brew --prefix)/opt/coreutils/libexec/gnubin:$PATH"{{end}}
        for FOLDER in project-*/; do
          SUBTYPE="$(echo "$FOLDER" | sed 's/project-\(.*\)\//\1/')"
          cp -rT "$FOLDER" "./{{.COMMON_FOLDER}}-$SUBTYPE"
        done

  merge:
    deps:
      - merge:package
      - merge:variables

  merge:package:
    cmds:
      - task: merge:package:project
      - task: merge:package:project:subtype

  merge:package:project:
    deps:
      - :install:software:jq
    log:
      error: Error merging `package.json.liquid` templates
      start: Merging `package.json.liquid` templates
      success: Merged `package.json.liquid` templates
    cmds:
      - |
        function ensureKeywords() {
          if [ ! -f "$1" ]; then echo "{}" > "$1"; fi
          KEYWORDS="$(jq -r '.keywords' "$1")"
          if [[ "$KEYWORDS" == 'null' ]] || [[ "$KEYWORDS" == '' ]]; then
            TMP="$(mktemp)"
            jq -r '.keywords = [] | .' "$1" > "$TMP"
            mv "$TMP" "$1"
          fi
        }

        function mergePackages() {
          # Ensure array exists in both JSON files
          ensureKeywords "$1"
          ensureKeywords "$2"

          # Merge the files
          TMP="$(mktemp)"
          jq --arg keywords "$(jq '.keywords[]' "$1" "$2" | jq -s '. | unique')" -s -S \
            '.[0] * .[1] | .keywords = ($keywords | fromjson) | .' "$1" "$2" > "$TMP"
          mv "$TMP" "$3"
        }

        mergePackages "./{{.SHARED_FOLDER}}/common/package.json.liquid" "./project/package.json.liquid" "./{{.COMMON_FOLDER}}/package.json.liquid"

  merge:package:project:subtype:
    deps:
      - :install:software:jq
    log:
      error: Error merging `package.json.liquid` templates for sub-type
      start: Merging `package.json.liquid` templates for sub-type
      success: Merged `package.json.liquid` templates for sub-type
    cmds:
      - |
        function ensureKeywords() {
          if [ ! -f "$1" ]; then echo "{}" > "$1"; fi
          KEYWORDS="$(jq -r '.keywords' "$1")"
          if [[ "$KEYWORDS" == 'null' ]] || [[ "$KEYWORDS" == '' ]]; then
            TMP="$(mktemp)"
            jq -r '.keywords = [] | .' "$1" > "$TMP"
            mv "$TMP" "$1"
          fi
        }

        function mergePackages() {
          # Ensure array exists in both JSON files
          ensureKeywords "$1"
          ensureKeywords "$2"

          # Merge the files
          TMP="$(mktemp)"
          jq --arg keywords "$(jq '.keywords[]' "$1" "$2" | jq -s '. | unique')" -s -S '.[0] * .[1] | .keywords = ($keywords | fromjson) | .' "$1" "$2" > "$TMP"
          mv "$TMP" "$3"
        }

        for FOLDER in project-*/; do
          SUBTYPE="$(echo "$FOLDER" | sed 's/project-\(.*\)\//\1/')"
          mergePackages "./{{.COMMON_FOLDER}}/package.json.liquid" "project-$SUBTYPE/package.json.liquid" "./{{.COMMON_FOLDER}}-$SUBTYPE/package.json.liquid" &
        done
        wait

  merge:variables:
    cmds:
      - task: merge:variables:project
      - task: merge:variables:subtype

  merge:variables:project:
    deps:
      - :install:software:jq
    log:
      error: Error merging variables files
      start: Merging variables.json files
      success: Merged variables.json files
    cmds:
      - |
        if [ -f "project/.config/variables.json" ]; then
          jq -s -S '.[0] * .[1]' "./{{.COMMON_FOLDER}}/.config/docs/variables.json" \
            "project/.config/variables.json" > "./{{.COMMON_FOLDER}}/.config/variables.json"
        else
          cp ./{{.COMMON_FOLDER}}/.config/docs/variables.json ./{{.COMMON_FOLDER}}/.config/variables.json
        fi

  merge:variables:subtype:
    deps:
      - :install:software:jq
    log:
      error: Error merging variables files for sub-type
      start: Merging variables.json files for sub-type
      success: Merged variables.json files for sub-type
    cmds:
      - |
        GROUP="$(jq -r '.blueprint.group' package.json)"
        if [[ "$GROUP" == 'null' ]]; then
          GROUP="$(yq e '.vars.REPOSITORY_TYPE' Taskfile.yml)"
          if [[ "$GROUP" == 'null' ]]; then
            echo "ERROR '.blueprint.group' did not exist in the package.json and the fallback '.vars.REPOSITORY_TYPE' did not exist in the Taskfile.yml"
          fi
        fi
        function handleSubtype() {
          FOLDER="$1"
          SUBTYPE="$(echo "$FOLDER" | sed 's/project-\(.*\)\//\1/')"
          mkdir -p "./{{.COMMON_FOLDER}}-$SUBTYPE/.config"
          TMP="$(mktemp)"
          jq --arg group "$GROUP" --arg subtype "$SUBTYPE" '.subgroup = $subtype | .group = $group | .' ./{{.COMMON_FOLDER}}/.config/variables.json > "$TMP"
          if [ -f "project-$SUBTYPE/.config/variables.json" ]; then
            jq -s -S '.[0] * .[1]' "$TMP" "project-$SUBTYPE/.config/variables.json" > "./{{.COMMON_FOLDER}}-$SUBTYPE/.config/variables.json"
          else
            mv "$TMP" "./{{.COMMON_FOLDER}}-$SUBTYPE/.config/variables.json"
          fi
        }
        for FOLDER in project-*/; do
          handleSubtype "$FOLDER" &
        done
        wait

  reset:
    log:
      error: Error removing `.common*` and `_generated_`
      start: Removing `.common*` and `_generated_`
      success: Removed `.common*` and `_generated_`
    cmds:
      - rm -rf .common*
      - rm -rf _generated_

  template:
    deps:
      - :install:modules:local
      - :install:npm:liquidjs
    cmds:
      - task: :upstream:variables
        vars:
          INPUT_FILE: ./{{.COMMON_FOLDER}}/.config/docs/variables.json
          OUTPUT_FILE: ./.variables.json
      - task: template:files

  template:files:
    deps:
      - template:files:liquidjs

  template:files:liquidjs:
    cmds:
      - task: :upstream:template:liquidjs
        vars:
          ADDITIONAL_IGNORE_FOLDERS: -path './{{.COMMON_FOLDER}}*' -o -path './project*' -o -path './deprecated*' -o