#!/bin/bash

# deploy.sh

source ${BASE_DIR}/config_vars.sh

usage() {
	echo "usage: $1 [--no_bootloader] [--no_kernel] [--no_rootfs] [--lazy_bootloader] [--lazy_kernel] [--lazy_rootfs] [<output directory>]"
	echo "     <output directory>: directory where deploy.tgz is written to, default is $out_dir"
	exit 1
}

keep_bootloader=0
keep_kernel=0
keep_rootfs=0
lazy_kernel=0
lazy_rootfs=0
lazy_bootloader=0

export last_dir=$PWD

cd $(dirname $0)
work_dir=$PWD
cd ..
out_dir=$PWD/packman_deploy
cd ${last_dir}

name=$0
while [ "$1" != "" ]
do
	if [ "$1" = --no_bootloader ]
	then
		keep_bootloader=1
	elif [ "$1" = --no_kernel ]
	then
		keep_kernel=1
	elif [ "$1" = --no_rootfs ]
	then
		keep_rootfs=1
	elif [ "$1" = --lazy_bootloader ]
	then
		lazy_bootloader=1
	elif [ "$1" = --lazy_kernel ]
	then
		lazy_kernel=1
	elif [ "$1" = --lazy_rootfs ]
	then
		lazy_rootfs=1
	elif [ -d "$1" ]
	then
		cd "$1"
		out_dir=$PWD
	else
		usage "$name"
		exit 1
	fi

	shift
done

cd ${work_dir}

td=/tmp/cvoctavo_deploy/deploy

if [ -e "$td" ]
then
	rm -rf "$td"
fi


mkdir -p "$td"

if ! [ -d "$td" ]
then
	echo "Kein Verzeichnis bzw. nicht als Verzeichnis erstellbar: $td"
fi

cp -r -L ../update/* "$td/"

if [ "$IS2T" = 1 ]
then
	echo "fw_setenv bootcmd echo \"'los gehts'; gpio clear 42; gpio clear 43; sleep 0.2; gpio set 43; if mmc rescan; then if load mmc 0:1 $loadaddr /boot.scr; then source $loadaddr; fi; fi; run my_nand_boot;\"" >> "$td/update_env.sh"
fi

rm "$td"/*~ 2>/dev/null
rm "$td"/intern/*~ 2>/dev/null

chmod +x "$td"/*.sh "$td"/intern/*.sh


./intern/copyImages.sh "$td"

if [ "$keep_bootloader" = 1 ]
then
	if ! rm "$td"/update_bootloader.sh "$td"/MLO "$td"/u-boot
	then
		exit 1
	fi
fi

if [ "$keep_kernel" = 1 ]
then
	if ! rm "$td"/update_kernel.sh "$td"/kernel
	then
		exit 1
	fi
fi

if [ "$keep_rootfs" = 1 ]
then
	if ! rm "$td"/update_rootfs.sh "$td/rootfs.ubi.tgz"
	then
		exit 1
	fi
fi

cp ${TARGET_DIR}/home/user/linuxbbsvnrev.txt "$td"/linuxbbsvnrev.txt

echo "$lazy_bootloader" >"$td"/lazy_bootloader.txt
echo "$lazy_kernel" >"$td"/lazy_kernel.txt
echo "$lazy_rootfs" >"$td"/lazy_rootfs.txt

if [ -f "${BASE_DIR}/setbootmsg2display.sh" ]
then
    echo "${BASE_DIR}/setbootmsg2display.sh" > "$td"/setbootmsg2display.sh
    cp "${BASE_DIR}/setbootmsg2display.sh" "$td"
fi

mkdir -p ${out_dir}

if ! tar -C "$(dirname $td)" -c -v -z -f "$out_dir"/deploy.tgz "$(basename $td)"
then
	echo "ERROR: Konnte $out_dir/deploy.tgz nicht mit tar erstellen, versuche sudo"
	if ! sudo tar -C "$(dirname $td)" -c -v -z -f "$out_dir"/deploy.tgz "$(basename $td)"
	then
		exit 1
	fi
fi
echo 'nach fraglichem tar'

echo "out_dir is $out_dir"

echo "\n** FERTIG: tar-ball erstellt:"
ls -l $(realpath "$out_dir"/deploy.tgz)

rm -rf "$td"
