#!/usr/bin/env bash
# Fetch the Alpine 3.21 NoCloud cloud-init image used as the Tier-1/2
# baseline guest. Convert to qcow2 if necessary; verify sha512 against
# the value pinned in docs/sources.md.
#
# Usage:
#   scripts/fetch-alpine-baseline.sh <out_path>
#
# Examples:
#   scripts/fetch-alpine-baseline.sh vm/images/alpine-baseline.qcow2
#   sudo scripts/fetch-alpine-baseline.sh /var/lib/cis490/vm/images/alpine-baseline.qcow2
#
# Idempotent — re-runs check the destination and short-circuit if the
# checksum already matches.

set -euo pipefail

OUT="${1:-}"
if [[ -z "$OUT" ]]; then
    echo "usage: $0 <out_path>" >&2
    exit 2
fi

URL="https://dl-cdn.alpinelinux.org/alpine/v3.21/releases/cloud/nocloud_alpine-3.21.0-x86_64-bios-cloudinit-r0.qcow2"
SHA512="bb509092cda3548c11bc48a2168ce950d654b50db006e98939c06a5d86487f4e53cbb7954fafbba9ab5c8098008a9f304421ffc3397b0bc1d87b6aa309239b98"

log() { printf '[fetch-alpine] %s\n' "$*" >&2; }

if [[ -f "$OUT" ]]; then
    actual="$(sha512sum "$OUT" | awk '{print $1}')"
    if [[ "$actual" == "$SHA512" ]]; then
        log "$OUT already present and verified"
        exit 0
    fi
    log "$OUT exists but checksum differs — refetching"
    rm -f "$OUT"
fi

mkdir -p "$(dirname "$OUT")"
TMP="$OUT.partial"
trap 'rm -f "$TMP"' EXIT

log "downloading $URL"
if command -v curl >/dev/null; then
    curl -fL --retry 3 --retry-delay 5 -o "$TMP" "$URL"
elif command -v wget >/dev/null; then
    wget -O "$TMP" "$URL"
else
    log "neither curl nor wget on PATH"
    exit 1
fi

log "verifying sha512"
actual="$(sha512sum "$TMP" | awk '{print $1}')"
if [[ "$actual" != "$SHA512" ]]; then
    log "sha512 mismatch: expected $SHA512, got $actual"
    exit 1
fi

mv "$TMP" "$OUT"
trap - EXIT
log "wrote $OUT ($(stat -c%s "$OUT") bytes)"
