stages:
  - build
  - deploy
  - bump-version

variables:
  INTERNAL_REGISTRY: "192.168.1.100:9080"
  IMAGE_NAME: "$INTERNAL_REGISTRY/$CI_PROJECT_PATH"
  CI_SERVER_URL: "http://192.168.1.100:9080"
  GITLAB_FEATURES: ""

docker-build:
  stage: build
  image:
    name: gcr.io/kaniko-project/executor:v1.23.2-debug
    entrypoint: [""]
  rules:
    - if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH
  before_script:
    - mkdir -p /kaniko/.docker
    - |
      cat > /kaniko/.docker/config.json <<EOF
      {
        "auths": {
          "$INTERNAL_REGISTRY": {
            "username": "$CI_REGISTRY_USER",
            "password": "$CI_REGISTRY_PASSWORD"
          }
        }
      }
      EOF
  script:
    - |
      VERSION=$(cat VERSION 2>/dev/null || echo "0.0.0")

      if [ "$CI_COMMIT_REF_NAME" = "main" ]; then
        TAG="main"
        CHANNEL="stable"
      elif [ "$CI_COMMIT_REF_NAME" = "feature/nightly" ] || [ "$CI_COMMIT_REF_NAME" = "nightly" ]; then
        TAG="nightly"
        VERSION="${VERSION}-nightly"
        CHANNEL="nightly"
      else
        CLEAN_TAG=$(echo "$CI_COMMIT_REF_NAME" | sed 's/\//-/g')
        TAG="$CLEAN_TAG"
        VERSION="${VERSION}-dev"
        CHANNEL="dev"
      fi

      DESTINATIONS="--destination=$IMAGE_NAME:$TAG"
      if [ "$CI_COMMIT_REF_NAME" = "main" ]; then
        DESTINATIONS="$DESTINATIONS --destination=$IMAGE_NAME:latest"
      fi

      echo "Building for channel $CHANNEL with version $VERSION and tag $TAG"

      /kaniko/executor \
        --context "$CI_PROJECT_DIR" \
        --dockerfile "$CI_PROJECT_DIR/Dockerfile" \
        --build-arg "VITE_BUILD_CHANNEL=$CHANNEL" \
        --build-arg "VITE_APP_VERSION=$VERSION" \
        --cache=true \
        --cache-repo="$IMAGE_NAME/cache" \
        --cache-ttl=168h \
        --snapshot-mode=redo \
        --compressed-caching=false \
        --insecure-registry=$INTERNAL_REGISTRY \
        $DESTINATIONS

electron-build:
  stage: build
  image: electronuserland/builder:wine
  rules:
    - if: $CI_COMMIT_BRANCH == "main"
      changes:
        - electron/**/*
        - VERSION
    - if: $CI_COMMIT_BRANCH == "main"
      when: manual
      allow_failure: true
  script:
    - |
      VERSION=$(cat VERSION 2>/dev/null || echo "0.0.0")
      echo "[Electron] Building v${VERSION} for Windows..."

      cd electron
      node -e "
        const pkg = require('./package.json');
        pkg.version = '${VERSION}';
        require('fs').writeFileSync('package.json', JSON.stringify(pkg, null, 2) + '\n');
      "
      npm ci --no-audit --no-fund
      npx electron-forge make --platform win32 --arch x64
  artifacts:
    paths:
      - electron/out/make/squirrel.windows/x64/
    expire_in: 1 hour

deploy:
  stage: deploy
  image: docker:latest
  needs: [docker-build]
  rules:
    - if: $CI_COMMIT_BRANCH == "main"
  variables:
    DEPLOY_IMAGE: "$INTERNAL_REGISTRY/root/gaming-hub:latest"
    CONTAINER_NAME: "gaming-hub"
  script:
    - echo "[Deploy] Logging into registry..."
    - echo "$CI_REGISTRY_PASSWORD" | docker login "$INTERNAL_REGISTRY" -u "$CI_REGISTRY_USER" --password-stdin
    - echo "[Deploy] Pulling $DEPLOY_IMAGE..."
    - docker pull "$DEPLOY_IMAGE"
    - echo "[Deploy] Stopping $CONTAINER_NAME..."
    - docker stop "$CONTAINER_NAME" || true
    - docker rm "$CONTAINER_NAME" || true
    - echo "[Deploy] Starting $CONTAINER_NAME..."
    - |
      docker run -d \
        --name "$CONTAINER_NAME" \
        --network pangolin \
        --restart unless-stopped \
        -p 8085:8080 \
        -e TZ=Europe/Berlin \
        -e NODE_ENV=production \
        -e PORT=8080 \
        -e DATA_DIR=/data \
        -e SOUNDS_DIR=/data/sounds \
        -e "NODE_OPTIONS=--dns-result-order=ipv4first" \
        -e ADMIN_PWD="$GAMING_HUB_ADMIN_PWD" \
        -e PCM_CACHE_MAX_MB=2048 \
        -e DISCORD_TOKEN_JUKEBOX="$GAMING_HUB_DISCORD_JUKEBOX" \
        -e DISCORD_TOKEN_RADIO="$GAMING_HUB_DISCORD_RADIO" \
        -v /mnt/cache/appdata/gaming-hub/data:/data:rw \
        -v /mnt/cache/appdata/dockge/container/jukebox/sounds/:/data/sounds:rw \
        "$DEPLOY_IMAGE"
    - docker ps --filter name="$CONTAINER_NAME" --format "ID={{.ID}} Status={{.Status}} Image={{.Image}}"

electron-deploy:
  stage: deploy
  image: docker:latest
  needs: [electron-build, deploy]
  rules:
    - if: $CI_COMMIT_BRANCH == "main"
      changes:
        - electron/**/*
        - VERSION
    - if: $CI_COMMIT_BRANCH == "main"
      when: manual
      allow_failure: true
  variables:
    CONTAINER_NAME: "gaming-hub"
  script:
    - |
      VERSION=$(cat VERSION 2>/dev/null || echo "0.0.0")
      SRC_DIR="electron/out/make/squirrel.windows/x64"

      echo "[Electron Deploy] Deploying v${VERSION} artifacts..."

      # Ensure downloads directory exists in container
      docker exec "$CONTAINER_NAME" mkdir -p /data/downloads

      # Copy RELEASES metadata
      docker cp "${SRC_DIR}/RELEASES" "${CONTAINER_NAME}:/data/downloads/RELEASES"

      # Copy nupkg (for Squirrel auto-update)
      for f in ${SRC_DIR}/*.nupkg; do
        docker cp "$f" "${CONTAINER_NAME}:/data/downloads/$(basename "$f")"
      done

      # Copy Setup.exe with stable name for download button
      SETUP_EXE=$(ls ${SRC_DIR}/*Setup*.exe 2>/dev/null | head -1)
      if [ -n "$SETUP_EXE" ]; then
        docker cp "$SETUP_EXE" "${CONTAINER_NAME}:/data/downloads/GamingHub-Setup.exe"
        echo "[Electron Deploy] Setup.exe deployed: $(basename "$SETUP_EXE")"
      fi

      echo "[Electron Deploy] Files in /data/downloads/:"
      docker exec "$CONTAINER_NAME" ls -lh /data/downloads/

bump-version:
  stage: bump-version
  image:
    name: alpine/git:latest
    entrypoint: [""]
  needs: [deploy]
  rules:
    - if: $CI_COMMIT_BRANCH == "main" && $CI_COMMIT_TITLE !~ /\[skip ci\]/
  script:
    - apk add --no-cache jq
    - |
      git config user.name "GitLab CI"
      git config user.email "ci@adriahub.de"
      git remote set-url origin "http://oauth2:${CI_PUSH_TOKEN}@192.168.1.100:9080/${CI_PROJECT_PATH}.git"
      git fetch origin main
      git checkout -f main
      git pull --rebase origin main

      VERSION=$(cat VERSION)
      MAJOR=$(echo "$VERSION" | cut -d. -f1)
      MINOR=$(echo "$VERSION" | cut -d. -f2)
      PATCH=$(echo "$VERSION" | cut -d. -f3)
      NEXT_PATCH=$((PATCH + 1))
      NEXT_VERSION="${MAJOR}.${MINOR}.${NEXT_PATCH}"

      echo "$NEXT_VERSION" > VERSION

      # Sync electron/package.json version
      jq --arg v "$NEXT_VERSION" '.version = $v' electron/package.json > electron/package.json.tmp
      mv electron/package.json.tmp electron/package.json

      echo "Bumped version: $VERSION -> $NEXT_VERSION (VERSION + electron/package.json)"

      git add VERSION electron/package.json
      git commit -m "v${NEXT_VERSION} [skip ci]"
      git push origin main
