#!/bin/sh
set -e

SUITE=xenial
ARCH=amd64

VMSW=KVM
if [ -n "$USE_LXC" ]; then
    VMSW=LXC
elif [ -n "$USE_VBOX" ]; then
    VMSW=VBOX
elif [ -n "$USE_DOCKER" ]; then
    VMSW=DOCKER
fi

usage() {
  echo "Usage: ${0##*/} [OPTION]..."
  echo "Make a clean copy of the base client."
  echo
  cat << EOF
  --help     display this help and exit
  --suite U  build suite U instead of xenial
  --arch A   build architecture A (e.g. i386) instead of amd64
EOF
}

if [ $# != 0 ] ; then
  while true ; do
    case "$1" in
      --help|-h)
        usage
        exit 0
        ;;
      --suite|-s)
        SUITE="$2"
        shift 2
        ;;
      --arch|-a)
        ARCH="$2"
        shift 2
        ;;
      --*)
        echo "unrecognized option $1"
        exit 1
        ;;
      *)
        break
        ;;
    esac
  done
fi

export LXC_SUITE=$SUITE
export LXC_ARCH=$ARCH

BASE=base-$SUITE-$ARCH
OUT=target-$SUITE-$ARCH

case $VMSW in
  KVM)
    qemu-img create -f qcow2 -o backing_file="$BASE.qcow2" "$OUT.qcow2"
    ;;
  LXC)
    cp -a --sparse=always $BASE $OUT
    libexec/config-bootstrap-fixup
    on-target -u root bash < target-bin/bootstrap-fixup
    ;;
  VBOX)
    VBoxManage snapshot "Gitian-${SUITE}-${ARCH}" restore "Gitian-Clean"
    ;;
  DOCKER)
    true #Docker doesn't need to do anything
    ;;
esac
