#!/bin/sh
# vim: set ts=4 sw=4 tw=0 et ft=sh fen fdm=marker :

# {{{ LICENSE

# Copyright (c) 2019, BaseAlt SPO
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of the <organization> nor the
#       names of its contributors may be used to endorse or promote products
#       derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# }}}

set -u ${DEBUG:+-x}

# {{{ Command line handling

PROG="${0##*/}"

die () {
    local exit_code="$1"
    shift

    echo "$*" >&2
    exit "$exit_code"
}


usage() {
    cat >&2 <<EOF
build-recovery-tar -- build recovery image in recovery.tar format

Usage: $PROG [options]

Options:
    -t,--rootfs=FILE            path to root FS tarball to wrap
    -o,--output=FILE            write output to FILE
    -d,--date=DATE              override the image generation date
    -n,--image-name=NAME        specify image name
    -c,--compress-comand=CMD    compress the tarball with given command
    -l,--line=LINE              use LINE for the recovery line

Common options:
    -h,--help                   print this message and exit
EOF

    exit "${1:-2}"
}

# Default values, if any:
ROOTFS_TARBALL=
OUTPUT_TARBALL=./recovery.tar
DATE=$(date +%Y%m%d)
IMAGE_NAME=
COMPRESS_COMMAND='gzip'
RECOVERY_LINE='  Start'

TEMP=$(getopt -o 't:o:d:n:c:l:h' \
        --long 'rootfs:,output:,date:,image-name:,compress-command:,line:,help' \
        -n "$PROG" -- "$@")

[ "$?" -eq 0 ] || usage 1

[ -z "${DEBUG:-}" ] || echo "$TEMP"

# Note the quotes around "$TEMP": they are essential!
eval set -- "$TEMP"
unset TEMP

while :; do
    case "$1" in
        -t|--rootfs) ROOTFS_TARBALL="$2"; shift 2;;
        -o|--output) OUTPUT_TARBALL="$2"; shift 2;;
        -d|--date) DATE="$2"; shift 2;;
        -n|--image-name) IMAGE_NAME="$2"; shift 2;;
        -c|--compress-command) COMPRESS_COMMAND="$2"; shift 2;;
        -l|--line) RECOVERY_LINE="$2"; shift 2;;
        -h|--help) usage 0;;
        --) shift; break;;
        *) die 1 "Unknown option: '$1'" ;;
    esac
done

[ "$#" -eq 0 ] || die 4 "Extra arguments"
[ -n "$ROOTFS_TARBALL" ] || die 10 "Please specify rootfs tarball"
[ -n "$IMAGE_NAME" ] || die 11 "Please specify image name"

[ -r "$ROOTFS_TARBALL" ] || die 21 "File $ROOTFS_TARBALL is not accesible"
[ -s "$ROOTFS_TARBALL" ] || die 22 "File $ROOTFS_TARBALL is empty"
[ ! -e "$OUTPUT_TARBALL" ] || die 23 "File $OUTPUT_TARBALL already exists"

# }}}

# {{{ Workdir

WORKDIR=$(mktemp -d /tmp/alt-recovery.XXXXXX)

cleanup() {
    rm -rf "$WORKDIR"
    exit "$1"
}

trap 'cleanup $?' EXIT
trap 'cleanup 1' HUP PIPE INT QUIT TERM

# }}}

# {{{ Now we can do that

export TZ=UTC

set -e
generate-recovery-rc "$IMAGE_NAME" "$DATE" > "$WORKDIR/recovery.rc"
$COMPRESS_COMMAND <  "$ROOTFS_TARBALL"     > "$WORKDIR/rootfs.tar.gz"
echo "$RECOVERY_LINE"                      > "$WORKDIR/line"

tar -C "$WORKDIR/" -cf "$OUTPUT_TARBALL" \
    ././rootfs.tar.gz ././line ././recovery.rc

# }}}
