#!/bin/sh

# FIXME: edit this lines before release
IPFVER=2.23
COREVER=$(cat /opt/pakfire/db/core/mine)

arch=$(uname -m)

case "${arch}" in
	aarch64|x86_64)
		;;
	i?86)
		arch="i586"
		;;
	*)
		echo "Arch is not supported" >&2
		exit 1
		;;
esac

URL="https://downloads.ipfire.org/releases/ipfire-2.x/$IPFVER-core$COREVER/"
ISO="ipfire-$IPFVER.$arch-full-core$COREVER.iso"

makeiso() {
	local dir="${1}"
	local output="${2}"

	local args=

	# Add EFI options when EFI image is present
	if [ -e "${dir}/boot/isolinux/efiboot.img" ]; then
		args="${args} -eltorito-alt-boot -e boot/isolinux/efiboot.img -no-emul-boot"
	fi

	# Compose ISO
	mkisofs -J -r -V "IPFire ${IPFVER} ${arch}" \
		-b boot/isolinux/isolinux.bin -no-emul-boot -boot-load-size 4 -boot-info-table \
		-c boot/isolinux/boot.catalog \
		${args} ${dir} > ${output}

	# Add DOS paritition table
	if [ -e "${dir}/boot/isolinux/efiboot.img" ]; then
		isohybrid --uefi ${output}
	else
		isohybrid ${output}
	fi

	return 0
}

if [ -z $1 ]; then
	echo usage: $0 backup-file
	exit
fi

TS=$1

mkdir -p /var/tmp/backupiso
cd /var/tmp/backupiso

if [ ! -f ${ISO} ]
then
	echo "Fetching ${URL}${ISO}"
	wget --quiet -c ${URL}${ISO}
fi

echo "Fetching ${URL}${ISO}.md5"
wget --quiet -O ${ISO}.md5 ${URL}${ISO}.md5

echo "Checking md5 of ${ISO}"
md5sum --status -c ${ISO}.md5
if [ $? -eq 0 ] || [ $? -eq 24 ]
then
	echo "md5 is OK"
else
	echo "md5 mismatch"
	echo "Fetching again ${URL}${ISO}"
	wget --quiet -O ${ISO} ${URL}${ISO}
	echo "Checking again md5 of ${ISO}"
	md5sum --status -c ${ISO}.md5
	if [ $? -eq 0 ] || [ $? -eq 24 ]
	then
		echo "md5 is OK"
	else
		echo "md5 mismatch"
		echo "aborting backup because md5 mismatch"
		exit 1
	fi
fi
rm ${ISO}.md5

echo "Remastering iso"
mkdir -p backupiso.tmp.${TS}
mount -o loop ${ISO} backupiso.tmp.${TS}
cp -pr backupiso.tmp.${TS} backupiso.${TS}
umount backupiso.tmp.${TS}
rm -r backupiso.tmp.${TS}

# Copy backup file to disk
cp "/var/ipfire/backup/${TS}.ipf" "backupiso.${TS}/backup.ipf"

# Add a version tag
touch "backupiso.${TS}/backup-${TS}.media"

echo "Running mkisofs"
makeiso backupiso.${TS} $(basename ${ISO} .iso)-${TS}.iso

echo "Cleaning up"
rm -rf backupiso.${TS}
