aboutsummaryrefslogtreecommitdiffstats
path: root/build-openbsd-image.sh
blob: a7bce6f875a77ecf87049131005804d9ebdb55fe (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#!/bin/sh
#
# DESCRIPTION:
#   Create an OpenBSD image with Packer and QEMU.
#
# USAGE:
#   ./build-openbsd-image.sh
set -o nounset
set -o errexit

_SCRIPT_DIR=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)
. "$_SCRIPT_DIR/lib.sh"

VERSION=8.0
ARCH=amd64
DISK_SIZE_GB=38
SSH_KEY="$HOME/.ssh/id_rsa.pub"
DISKLABEL_TEMPLATE=""

export PACKER_LOG=1

main() (
  parse_args "$@"
  cd openbsd-image/
  require_readable_file "$SSH_KEY"
  if [ -n "$DISKLABEL_TEMPLATE" ]; then
    require_readable_file "$DISKLABEL_TEMPLATE"
  fi
  if [ -d build/ ]; then
    printf 'Build directory exists. Must delete before re-building. Proceed? (y/N)'
    read -r answer
    case $answer in
    [yY])
      echo "Removing build/.."
      rm -r build/
      ;;
    *)
      echo "Aborting.."
      exit 0
      ;;
    esac
  fi
  packer init .
  packer build \
    -only "qemu.openbsd-$ARCH" \
    -var "arch=$ARCH" \
    -var "disk_size=$DISK_SIZE_GB" \
    -var "version=$VERSION" \
    -var "ssh_key=$(cat "$SSH_KEY")" \
    -var "cpus=$(get_ncpus)" \
    ${DISKLABEL_TEMPLATE:+-var "disklabel_template=$(cat "$DISKLABEL_TEMPLATE")"} \
    .
)

parse_args() {
  while [ $# -gt 0 ]; do
    case "$1" in
    -h | --help)
      usage
      exit 0
      ;;
    --version)
      VERSION="$2"
      shift 2
      ;;
    --arch)
      ARCH="$2"
      shift 2
      ;;
    --disk-size-gb)
      DISK_SIZE_GB="$2"
      shift 2
      ;;
    --ssh-key)
      SSH_KEY="$2"
      shift 2
      ;;
    --disklabel-template)
      DISKLABEL_TEMPLATE="$(realpath "$2")"
      shift 2
      ;;
    *)
      echo "Unknown option: $1"
      shift
      ;;
    esac
  done
}

usage() {
  cat <<EOF
Usage: $(basename "$0") [OPTIONS]

Create an OpenBSD image with Packer and QEMU.

Options:
  --version VERSION             OpenBSD version to build (default: $VERSION)
  --arch ARCH                   Target architecture: amd64 or arm64 (default: $ARCH)
  --disk-size-gb SIZE           Disk size in GB (default: $DISK_SIZE_GB)
  --ssh-key PATH                Path to SSH key (default: $SSH_KEY)
  --disklabel-template PATH     Path to a custom disklabel autopartition template.
                                If omitted, uses OpenBSD's default auto layout.
  -h, --help                    Show this help message
EOF
}

main "$@"