#!/bin/bash
set -e -u


# Translates a multistrap configuration template into a configuration file.

USAGE="Usage: ${0##./} [-i <template-file>] [-o <output-file>] [-p <package-name>] [-r <repo-url>] [-s <suitename>] [-t <tarfile>.tgz]
Options:
    -i  input (template) file name (omit for stdin)
    -o  output filename (omit for stdout)
    -p  package name (can be repeated)
    -r  repository source URL, i.e. 'copy://\$HOME/repo'
    -s  suite name, i.e. 'buster' (omit for 'unstable')
    -t  tarfile name
    -H  hookdir <internal use only>
"

infile=${infile:-"/dev/stdin"}
outfile=${outfile:-"/dev/stdout"}
suitename=${suitename:-"unstable"}
sourceurl=${sourceurl:-"copy:///mnt/repo"}
tarfile=${tarfile:-""}
package=""
hookdir=""

fatal () {
	echo "$@" >&2
	exit 1
}

while [ "$#" != 0 ]
do
    case "$1,${2-}" in
        -i,?*)
            infile="$2"
            shift
            shift
            ;;
        -o,?*)
            outfile="$2"
            shift
            shift
            ;;
        -p,?*)
            case "${package}x" in
                x) package="$2" ;;
                *) package="${package} $2" ;;
            esac
            shift
            shift
            ;;
        -r,?*)
            sourceurl="$2"
            shift
            shift
            ;;
        -s,?*)
            suitename="$2"
            shift
            shift
            ;;
        -t,?*)
            tarfile="$2"
            shift
            shift
            ;;
        -H,?*)
            hookdir="$2"
            shift
            shift
            ;;
        -*)
            fatal "$USAGE"
            ;;
        *)
            fatal "$USAGE"
            ;;
    esac
done

cat $infile | sed \
                  -e "s!{{device-package}}!${package}!g" \
                  -e "s!{{dist-codename}}!${suitename}!g" \
                  -e "s!{{source-url}}!${sourceurl}!g" \
                  -e "s!{{tarfile-name}}!${tarfile}!g" \
                  -e "s!{{hookdir-name}}!${hookdir}!g" \
                  > $outfile
