image:
  name: alpine/helm:latest
  entrypoint: [ "/bin/bash", "-c" ]

stages:
  - release

release:
  stage: release
  rules:
  - if: '$CI_COMMIT_BRANCH =~ /^main/'
    when: always
  - when: never
  script:
    - |
      cd $CI_PROJECT_DIR
      for i in $(git show --pretty="" --name-only | grep '^charts/.*/Chart.yaml' | cut -d/ -f2); do
        pack=$(helm package ./charts/$i | sed 's/Success.*: \(.*\)/\1/')
        if [ ! -z $pack ]; then
          chart=$(basename $pack)
          curl --request POST \
               --user gitlab-ci-token:$CI_JOB_TOKEN \
               --form "chart=@${chart}" \
               "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/helm/api/stable/charts"
        fi
      done

rebuild:
  stage: release
  rules:
    - when: manual
      allow_failure: true
  script:
    - |
      cd $CI_PROJECT_DIR
      for i in $(find ./charts -maxdepth 2 -name Chart.yaml | cut -d/ -f3); do
        pack=$(helm package ./charts/$i | sed 's/Success.*: \(.*\)/\1/')
        if [ ! -z $pack ]; then
          chart=$(basename $pack)
          curl --request POST \
               --user gitlab-ci-token:$CI_JOB_TOKEN \
               --form "chart=@${chart}" \
               "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/helm/api/stable/charts"
        fi
      done

