stages:
  - mirror
  - build
  - deploy

variables:
  IMAGE_NAME: purwakarta-diskominfo-simedkom-new
  IMAGE_TAG: v1.0.0
  CONTAINER_NAME: purwakarta-diskominfo-simedkom-new

mirror:
  stage: mirror
  image: alpine:latest
  tags:
    - docker

  variables:
    GIT_DEPTH: 0

  before_script:
    - apk add --no-cache git

  script:
    - git config --global user.email "mirror@pratama.live"
    - git config --global user.name "Pratama CI Mirror"

    - git checkout $CI_COMMIT_REF_NAME

    - rm -f .gitlab-ci.yml Dockerfile docker-compose.yml
    - rm -rf .gitlab

    - git add -A
    - TREE=$(git write-tree)
    - ORIGINAL_COMMIT=$(git rev-parse --short HEAD)
    - COMMIT=$(echo "Automated mirror from main@$ORIGINAL_COMMIT" | git commit-tree $TREE -p HEAD)

    - git remote remove pwk || true
    - git remote add pwk https://$MIRROR_PWK_USERNAME:$MIRROR_PWK_TOKEN@$MIRROR_PWK_URL

    - git push pwk $COMMIT:refs/heads/dev --force
  only:
    - main

build:
  stage: build
  timeout: 60m
  image: docker:latest
  services:
    - docker:dind
  tags:
    - docker
  script:
    - docker info
    - docker build -t $IMAGE_NAME:$IMAGE_TAG .

deploy:
  stage: deploy
  timeout: 60m
  image: docker:latest
  services:
    - docker:dind
  tags:
    - docker
  before_script:
  - echo -e "$ENV_FILE" > .env
  script:
    - docker compose down || true
    - docker compose up -d
  only:
    - main
