#!/bin/bash

if [ -z "$1" ] || [ -z "$2" ]; then
    echo "instdist.sh <zip-file> <path-to-mount-root>"
    echo "Installs a distribution zip (made with mkdist) on an SD card"
    echo "<path-to-mount-root> is where the rootfs and BOOT folders are"
    echo " /var/run/media/<username> for CentOS"
    exit 0
fi

TMPDIR=$(mktemp -d)

# Bail out if the temp directory wasn't created successfully.
if [ ! -e $TMPDIR ]; then
    echo "Failed to create temp directory"
    exit 1
fi

# Make sure it gets removed even if the script exits abnormally.
trap "exit 1"           HUP INT PIPE QUIT TERM
trap 'rm -rf "$TMPDIR"' EXIT

# unzip TMP dir
unzip $1 -d $TMPDIR

cp $TMPDIR/BOOT/* $2/BOOT/.
sudo tar -xvzf $TMPDIR/rootfs.tar.gz -C $2/rootfs/
echo "Unmounting, please wait..."
sudo umount $2/BOOT $2/rootfs

