#!/usr/bin/env bash set -Eeuo pipefail if [[ $# -lt 1 || $# -gt 2 ]]; then printf 'Usage: %s SHARD [OUTPUT.vcf.gz]\n' "${0##*/}" >&2 exit 2 fi script_dir="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)" repo_root="$(CDPATH= cd -- "$script_dir/.." && pwd)" shard="$1" output="${2:-$repo_root/exported/$shard.vcf.gz}" threads="${THREADS:-4}" plink2="${PLINK2:-$repo_root/.tools/plink2-20260818/plink2}" if [[ ! -x "$plink2" ]]; then plink2="$(command -v plink2 || true)" fi bcftools="${BCFTOOLS:-$(command -v bcftools || true)}" [[ -n "$plink2" && -x "$plink2" ]] || { printf 'PLINK 2 not found; set PLINK2\n' >&2; exit 127; } [[ -n "$bcftools" && -x "$bcftools" ]] || { printf 'bcftools not found; set BCFTOOLS\n' >&2; exit 127; } materialized="$repo_root/work/materialized/$shard" prefix="$materialized/$shard" export_work="$repo_root/work/export/$shard" export_prefix="$export_work/$shard" mkdir -p "$export_work" "$(dirname -- "$output")" if [[ ! -f "$prefix.pgen" ]]; then "$script_dir/materialize-shard.sh" "$shard" "$materialized" fi rm -f "$export_prefix.vcf.gz" "$export_prefix.vcf.gz.tbi" "$plink2" \ --pfile "$prefix" vzs \ --export vcf-4.2 bgz id-paste=iid \ --output-chr chrM \ --out "$export_prefix" mv "$export_prefix.vcf.gz" "$output" "$bcftools" index --force --tbi --threads "$threads" "$output" printf 'Exported PLINK-retained fields: %s\n' "$output" printf 'Created Tabix index: %s.tbi\n' "$output"