#!/bin/sh

# Copyright (c) 2013 SpinetiX S.A.
#
# media-mount hook for updater
#
# This script takes care of installing the necessary bind
# mounts when storage is added or removed by media-mount
# and the mounted storage has firmware update files.
#
# Input environment variables:
#
# MNTDIR: the directory where the filesystem was mounted
# MNTDEV: the device that was mounted
#

# The mount point for updates
UPDATES_MPT=/var/lib/updater/mnt-usb-updates

# Load general helpers and config
[ -f /etc/media-mount/media-mount-functions ] || exit 1
. /etc/media-mount/media-mount-functions
load_sysconfig

add_bind_mount() {
    local entry
    local src="$1"
    local dst="$2"

    if ! mktmpfstab; then
	echo "ERROR: cannot create temporary fstab while adding mounts for $MNTDEV"
	return 1
    fi

    entry="$src $dst none bind,noauto 0 0"
    echo "INFO: adding '$entry' to fstab"
    echo "$entry" >> "$TMPFSTAB"
    if [ $? -eq 0 ]; then
	savetmpfstab
    else
	rmtmpfstab
	return 1
    fi
}

add() {
    if [ ! -f "$MNTDIR"/updates/repodata/repomd.xml ]; then
	return 0 # no updates file here
    fi

    if is_any_mounted_at "$UPDATES_MPT"; then
	echo "WARN: USB storage contains updates but one is already mounted for updates"
	return 0
    fi

    add_bind_mount "${MNTDIR%/}"/"updates" "$UPDATES_MPT"
    if [ $? -ne 0 ]; then
	echo "ERROR: failed adding bind mount for updates"
	return 1
    fi

    if [ ! -e "$UPDATES_MPT" ] && ! mkdir -p "$UPDATES_MPT"; then
	echo "ERROR: failed creating mount point '$UPDATES_MPT'"
	return 1
    fi

    mount "$UPDATES_MPT"
    if [ $? -ne 0 ]; then
	echo "ERROR: failed mounting new bind mount"
	return 1
    fi

    return 0
}

remove() {
    return 0 # nothing to do
}

#
# Main
#

case "$1" in
    add)
	add
	;;
    remove)
	remove
	;;
    *)
	;;
esac
