name: Build Offline Terraform Installer

on:
  push:
    paths:
      - '.github/workflows/offline-package-terraform-installer.yaml'
  workflow_dispatch:
    inputs:
      tag:
        description: "Release tag to use/sync (e.g., v1.8.5). Leave empty to use offline-terraform-<run_number>"
        required: false
        type: string
      terraform_version:
        description: "Override Terraform version (e.g., 1.8.5). Leave empty to auto-resolve"
        required: false
        type: string

permissions:
  contents: write

concurrency:
  group: build-offline-terraform
  cancel-in-progress: false

jobs:
  build-offline-installer:
    strategy:
      matrix:
        arch: [amd64, arm64]
    runs-on: ubuntu-latest
    outputs:
      version: ${{ steps.resolve.outputs.version }}
    steps:
      - uses: actions/checkout@v4

      - name: Install deps (curl, jq, unzip)
        run: |
          set -euo pipefail
          sudo apt-get update -y
          sudo apt-get install -y curl jq unzip

      - name: Resolve Terraform version
        id: resolve
        env:
          OVERRIDE_VERSION: ${{ github.event.inputs.terraform_version }}
        run: |
          set -euo pipefail
          if [ -n "${OVERRIDE_VERSION}" ]; then
            VERSION="${OVERRIDE_VERSION}"
          else
            VERSION=$(curl -fsSL https://checkpoint-api.hashicorp.com/v1/check/terraform | jq -r '.current_version')
          fi
          echo "Resolved Terraform version: ${VERSION}"
          echo "version=${VERSION}" >> "$GITHUB_OUTPUT"

      - name: Build offline Terraform package
        env:
          TERRAFORM_VERSION: ${{ steps.resolve.outputs.version }}
        run: |
          set -euo pipefail
          ARCH="${{ matrix.arch }}"
          WORKDIR="terraform-offline-package"
          rm -rf "${WORKDIR}"
          mkdir -p "${WORKDIR}/"{bin,scripts,docs}

          BASE_URL="https://releases.hashicorp.com/terraform/${TERRAFORM_VERSION}"
          ARCHIVE="terraform_${TERRAFORM_VERSION}_linux_${ARCH}.zip"
          echo "Downloading ${BASE_URL}/${ARCHIVE}"
          curl -fSL "${BASE_URL}/${ARCHIVE}" -o "${ARCHIVE}"

          unzip -d "${WORKDIR}/bin" "${ARCHIVE}"
          rm -f "${ARCHIVE}"

          echo "${TERRAFORM_VERSION}" > "${WORKDIR}/VERSION"

          cat <<'SCRIPT' > "${WORKDIR}/scripts/install-terraform.sh"
#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
BIN="${ROOT_DIR}/bin/terraform"
INSTALL_DIR="${INSTALL_DIR:-/usr/local/bin}"

usage() {
  cat <<USAGE
Usage: $(basename "$0") [--install]
  --install    Copy terraform binary into ${INSTALL_DIR}
USAGE
}

if [[ "${1:-}" == "--install" ]]; then
  sudo install -m 0755 "$BIN" "${INSTALL_DIR}/terraform"
  echo "Terraform installed to ${INSTALL_DIR}/terraform"
else
  usage
fi
SCRIPT
          chmod +x "${WORKDIR}/scripts/install-terraform.sh"

          tar -czf "terraform-offline-package-${ARCH}.tar.gz" "${WORKDIR}"
          ls -lh "terraform-offline-package-${ARCH}.tar.gz"

      - name: Upload artifact
        uses: actions/upload-artifact@v4
        with:
          name: terraform-offline-package-${{ matrix.arch }}
          path: terraform-offline-package-${{ matrix.arch }}.tar.gz
          if-no-files-found: error

  test-offline-installer:
    needs: build-offline-installer
    strategy:
      matrix:
        arch: [amd64, arm64]
    runs-on: ubuntu-latest
    steps:
      - name: Download artifact
        uses: actions/download-artifact@v4
        with:
          name: terraform-offline-package-${{ matrix.arch }}
          path: ./test-dir

      - name: Extract package
        run: |
          set -euo pipefail
          cd test-dir
          tar -xzvf terraform-offline-package-${{ matrix.arch }}.tar.gz

      - name: Verify Terraform bundle
        env:
          TERRAFORM_VERSION: ${{ needs.build-offline-installer.outputs.version }}
        run: |
          set -euo pipefail
          cd test-dir/terraform-offline-package
          test -f VERSION
          if [ "${{ matrix.arch }}" = "amd64" ]; then
            ./bin/terraform version
            ./bin/terraform version | grep "Terraform v${TERRAFORM_VERSION}"
          else
            file ./bin/terraform | grep -E "ARM|aarch64"
          fi

  publish-release:
    needs: test-offline-installer
    runs-on: ubuntu-latest
    env:
      TAG_NAME: ${{ github.event.inputs.tag != '' && github.event.inputs.tag || format('offline-terraform-{0}', github.run_number) }}
      RSYNC_SSH_KEY: ${{ secrets.RSYNC_SSH_KEY }}
      RSYNC_SSH_USER: ${{ secrets.RSYNC_SSH_USER }}
      VPS_HOST: ${{ secrets.VPS_HOST }}
      REMOTE_ROOT: /data/update-server/terraform
    steps:
      - uses: actions/checkout@v4

      - name: Create GitHub Release
        id: create_release
        uses: actions/create-release@v1
        with:
          tag_name: ${{ env.TAG_NAME }}
          release_name: Build ${{ env.TAG_NAME }}
          draft: false
          prerelease: false
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Download amd64 artifact
        uses: actions/download-artifact@v4
        with:
          name: terraform-offline-package-amd64
          path: release-artifacts/amd64

      - name: Download arm64 artifact
        uses: actions/download-artifact@v4
        with:
          name: terraform-offline-package-arm64
          path: release-artifacts/arm64

      - name: Upload offline installers to GitHub Release
        uses: softprops/action-gh-release@v1
        with:
          tag_name: ${{ env.TAG_NAME }}
          files: |
            release-artifacts/amd64/terraform-offline-package-amd64.tar.gz
            release-artifacts/arm64/terraform-offline-package-arm64.tar.gz
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Ensure deps (rsync, ssh)
        run: |
          set -euo pipefail
          sudo apt-get update -y
          sudo apt-get install -y rsync openssh-client

      - name: Init SSH
        run: |
          set -euo pipefail
          mkdir -p ~/.ssh
          echo "$RSYNC_SSH_KEY" > ~/.ssh/id_rsa
          chmod 600 ~/.ssh/id_rsa
          ssh-keyscan -H "$VPS_HOST" >> ~/.ssh/known_hosts

      - name: Rsync release assets to remote
        run: |
          set -euo pipefail
          REMOTE_DIR="${REMOTE_ROOT}/${TAG_NAME}"
          ssh -i ~/.ssh/id_rsa "${RSYNC_SSH_USER}@${VPS_HOST}" "mkdir -p '${REMOTE_DIR}'"
          echo "Rsync -> ${VPS_HOST}:${REMOTE_DIR}/"
          rsync -av -e "ssh -i ~/.ssh/id_rsa" \
            release-artifacts/amd64/terraform-offline-package-amd64.tar.gz \
            release-artifacts/arm64/terraform-offline-package-arm64.tar.gz \
            "${RSYNC_SSH_USER}@${VPS_HOST}:${REMOTE_DIR}/"

  retention:
    name: Remote retention (keep latest 3)
    needs: publish-release
    runs-on: ubuntu-latest
    env:
      RSYNC_SSH_KEY: ${{ secrets.RSYNC_SSH_KEY }}
      RSYNC_SSH_USER: ${{ secrets.RSYNC_SSH_USER }}
      VPS_HOST: ${{ secrets.VPS_HOST }}
      REMOTE_ROOT: /data/update-server/terraform
    steps:
      - name: Init SSH
        run: |
          set -euo pipefail
          mkdir -p ~/.ssh
          echo "$RSYNC_SSH_KEY" > ~/.ssh/id_rsa
          chmod 600 ~/.ssh/id_rsa
          ssh-keyscan -H "$VPS_HOST" >> ~/.ssh/known_hosts

      - name: Prune old versions on remote (keep 3)
        run: |
          set -euo pipefail
          ssh -i ~/.ssh/id_rsa "${RSYNC_SSH_USER}@${VPS_HOST}" bash -lc '
            set -euo pipefail
            cd "'"${REMOTE_ROOT}"'" || exit 0
            keep=3
            mapfile -t all < <(ls -1 | grep -E "^(offline-terraform-|v[0-9]+\.)" | sort -V -r || true)
            if [ "${#all[@]}" -le "$keep" ]; then
              echo "Nothing to prune. Count=${#all[@]}"
              exit 0
            fi
            to_delete=("${all[@]:keep}")
            echo "Pruning old versions: ${to_delete[*]}"
            for d in "${to_delete[@]}"; do
              rm -rf -- "$d"
            done
          '
