version: "3"

silent: true

vars:
  BANNER: 'echo -e "\\033[1;33m$\\033[0m"'
  SNIPRAW_LOCAL: "C:\\Users\\patppuccin\\Documents\\Snipraw-Snippets"
  SNIPRAW_REMOTE: "hestia-sync:/home/patppuccin/snipraw/snippets/"
  SYNC_EXCLUDES: >-
    --exclude ".terraform/**"
    --exclude "**/.terraform.lock.hcl"
    --exclude ".git/**"
    --exclude "*.tfstate"
    --exclude "*.tfstate.backup"
    --exclude "archives/**"

tasks:
  default:
    desc: List available tasks
    cmds:
      - echo ">> run 'task --list' to see available tasks"

  sync:snippets:
    desc: "Sync local snippets to Hestia"
    cmds:
      - "{{.BANNER}} Syncing snippets to Hestia"
      - rclone sync "{{.SNIPRAW_LOCAL}}" {{.SNIPRAW_REMOTE}} --progress --create-empty-src-dirs {{.SYNC_EXCLUDES}}

  generate:policy-evals:
    desc: "Generates policy evaluation fixtures"
    preconditions:
      - sh: test -n "{{.CLI_ARGS}}"
        msg: "FIXTURE PATH MISSING - invoke using 'task generate:policy-evals -- <fixture-name>'"
      - sh: "set -- {{.CLI_ARGS}}; test $# -eq 1"
        msg: "TOO MANY ARGUMENTS - pass exactly one fixture name"
    vars:
      STACK_NAME:
        sh: |
          set -- {{.CLI_ARGS}}
          echo "$1"
      STACK_PATH: "{{.ROOT_DIR}}/tests/policy-evaluations/{{.STACK_NAME}}"
      FIXTURE_FILE: "{{.STACK_NAME}}.tfplan.json"
      DEST_DIR: "{{.ROOT_DIR}}/repos/iac-policies/fixtures"
      DEST_PATH: "{{.DEST_DIR}}/{{.FIXTURE_FILE}}"
    cmds:
      - "{{.BANNER}} Generating policy evaluation fixture for '{{.STACK_NAME}}'"
      - terraform -chdir="{{.STACK_PATH}}" init
      - terraform -chdir="{{.STACK_PATH}}" plan -out=tfplan.binary
      - terraform -chdir="{{.STACK_PATH}}" show -json tfplan.binary > "{{.STACK_PATH}}/{{.FIXTURE_FILE}}"
      - mkdir -p "{{.DEST_DIR}}"
      - cp "{{.STACK_PATH}}/{{.FIXTURE_FILE}}" "{{.DEST_PATH}}"
      - echo "Copied fixture to {{.DEST_PATH}}"

  cleanup:
    desc: "Performs general cleanup of iac-scaffold"
    cmds:
      - "{{.BANNER}} Cleaning up .terraform directories"
      - cmd: powershell -NoProfile -Command "Get-ChildItem -Path '{{.SNIPRAW_LOCAL}}' -Recurse -Directory -Filter '.terraform' | Remove-Item -Recurse -Force"
        platforms: [windows]
      - cmd: find {{.SNIPRAW_LOCAL}} -type d -name ".terraform" -exec rm -rf {} +
        platforms: [linux, darwin]
      - "{{.BANNER}} Cleaning up .terraform.lock.hcl files"
      - cmd: powershell -NoProfile -Command "Get-ChildItem -Path '{{.SNIPRAW_LOCAL}}' -Recurse -File -Filter '.terraform.lock.hcl' | Remove-Item -Force"
        platforms: [windows]
      - cmd: find {{.SNIPRAW_LOCAL}} -type f -name ".terraform.lock.hcl" -exec rm -f {} +
        platforms: [linux, darwin]
