# TODO: Add additional installers for all prerequisites that get skipped if
# the programs are already installed.

# Known additional prerequisites on Windows:
#   - Git and bash, both added to path
#   - For running VMM tests, Hyper-V and WHP must be enabled
#   - Visual Studio Build Tools
#     - Microsoft.VisualStudio.Component.VC.Tools.x86.x64
#     - Microsoft.VisualStudio.Component.VC.Tools.ARM64
#     - Microsoft.VisualStudio.Component.Windows11SDK.22621
#     - Microsoft.VisualStudio.Component.VC.Llvm.Clang (added to path)

#### Flowey Build Dependencies

# On Linux, install gcc and rust to build flowey.
# The apt-get retries below avoid failures in CI that can be
# intermittently caused by other processes temporarily holding
# the necessary dpkg or apt locks.
- run: |
    set -x
    i=0; while [ $i -lt 5 ] && ! sudo apt-get update; do let "i=i+1"; sleep 1; done;
    sudo apt-get -o DPkg::Lock::Timeout=60 install gcc -y
    curl --fail --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- --default-toolchain={{RUSTUP_TOOLCHAIN}} -y
    . "$HOME/.cargo/env"
    echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
    rustup show
  if: runner.os == 'Linux'
  name: rustup (Linux)
  shell: bash

# Building flowey on Windows requires MSVC from Visual Studio Build Tools,
# but that currently needs to be preinstalled on the actions runner.
- run: |
    set -x
    curl --fail -sSfLo rustup-init.exe https://win.rustup.rs/x86_64 --output rustup-init
    ./rustup-init.exe -y --default-toolchain={{RUSTUP_TOOLCHAIN}}
    echo "$USERPROFILE\\.cargo\\bin" >> $GITHUB_PATH
  if: runner.os == 'Windows' && runner.arch == 'X64'
  name: rustup (Windows X64)
  shell: bash

- run: |
    set -x
    curl --fail -sSfLo rustup-init.exe https://win.rustup.rs/aarch64 --output rustup-init
    ./rustup-init.exe -y --default-toolchain={{RUSTUP_TOOLCHAIN}}
    echo "$USERPROFILE\\.cargo\\bin" >> $GITHUB_PATH
  if: runner.os == 'Windows' && runner.arch == 'ARM64'
  name: rustup (Windows ARM64)
  shell: bash

#### Build Flowey

- uses: actions/checkout@v4
  with:
    path: flowey_bootstrap

# - CARGO_INCREMENTAL=0 - no need to waste time on incremental artifacts in CI
# - RUSTC_BOOTSTRAP=1 + RUSTFLAGS="-Z threads=8" - use of the unstable parallel
#   frontend to go f a s t
- name: Build flowey
  run: |
    set -x
    CARGO_INCREMENTAL=0 RUSTC_BOOTSTRAP=1 RUSTFLAGS="-Z threads=8" cargo build -p {{FLOWEY_CRATE}} --target {{FLOWEY_TARGET}} --profile flowey-ci
    OutDirNormal=$(echo "{{FLOWEY_OUTDIR}}" | sed -e 's|\\|\/|g' -e 's|^\([A-Za-z]\)\:/\(.*\)|/\L\1\E/\2|')
    mkdir -p "$OutDirNormal"
    mv ./{{FLOWEY_PIPELINE_PATH}}.yaml "$OutDirNormal/pipeline.yaml"
    mv target/{{FLOWEY_TARGET}}/flowey-ci/{{FLOWEY_CRATE}}{{FLOWEY_BIN_EXTENSION}} "$OutDirNormal/flowey{{FLOWEY_BIN_EXTENSION}}"
  working-directory: flowey_bootstrap
  shell: bash
