#!/bin/bash

# This script converts from the old to the new conventions
# used by the basic video modes configurator, so that display of
# values to user remains consistent.

conf="$1"

if [ -z "$1" ]; then
    echo "missing video mode settings file to upgrade" >&2
    exit 1
fi

# Read the settings
. "$conf"

# continue only if the old configurator was used
[ "$CONFIGURATOR_VERSION" = "" ] || exit 0

# exit if we do not match basic mode prerequisistes
[ "$USE_FIXED_MODEDB" = "yes" ] || exit 0
[ "$HDMI_UNDERSCAN_IGNORE" = '' ] || exit 0
[ "$FORCE_VFREQ" = "60" ] || exit 0
[ "$FORCE_AR" = '' ] || exit 0

# get the substitutions or exit if nothing to do
case "$RESOLUTION:$FIXED_MODE_TYPES" in
    "ED:hdmi")
	RESOLUTION="720x480"
	;;
    "ED:vesa")
	RESOLUTION="800x600"
	;;
    "ED:vesa,gtf")
	RESOLUTION="768x480"
	;;
    "HD:hdmi")
	RESOLUTION="1280x720"
	;;
    "HD:vesa")
	RESOLUTION="1024x768"
	;;
    "HD:vesa,gtf")
	RESOLUTION="1024x640"
	;;
    *)
	exit 0;
esac

# generate new file
newconf="$(mktemp "$conf".XXXXXX)"
if [ $? -ne 0 ]; then
    echo 'could not create temporary file to update video mode settings' >&2
    exit 1
fi
sed -e "s|^RESOLUTION=.*|RESOLUTION=${RESOLUTION}|" "$conf" > "$newconf" && \
    echo -e '\n# The version of the configurator used\nCONFIGURATOR_VERSION=2' >> "$newconf"
if [ $? -ne 0 ]; then
    echo 'failed converting video mode settings' >&2
    rm -f "$newconf"
    exit 1
fi
mv -f "$newconf" "$conf"
if [ $? -ne 0 ]; then
    echo 'failed replacing video mode settings with converted ones' >&2
    rm -f "$newconf"
    exit 1
fi
