#!/bin/bash
IMAGE_VERSION="/etc/image-version"
APT_FOLDER="/etc/apt"
OPKG_FOLDER="/etc/opkg"
OLD_APT="feed.dreamboxtools.de"
OLD_IPK="feed.merlin3.info"
NEW="merlinfeed.boxpirates.to"
DPATH_IPK="/etc/opkg/*.conf"
DPATH_APT="/etc/apt/*.list"
TFILE="/tmp/out.tmp.$$"

if [[ -f $IMAGE_VERSION ]]; then
	reseller=$(cat $IMAGE_VERSION | grep creator | cut -d"=" -f2)
	reseller=${reseller,,}
	if [[ $reseller == *"merlin"* ]]; then
		echo "... image is merlin"
		if [[ -d $APT_FOLDER ]]; then
			echo "... image is oe2.5 or oe2.6"
			for f in $DPATH_APT
			do
  				if [ -f $f -a -r $f ]; then
   					sed "s|$OLD_APT|$NEW|g" "$f" > $TFILE && mv $TFILE "$f"
  				else
   					echo "Error: Cannot read $f"
  				fi
			done
			echo "... new merlin-feed installed"
			apt-get update
			echo "... apt-get update executed"
		elif [[ -d $OPKG_FOLDER ]]; then
			echo "... image is oe2.0"
			for f in $DPATH_IPK
			do
  				if [ -f $f -a -r $f ]; then
   					sed "s|$OLD_IPK|$NEW|g" "$f" > $TFILE && mv $TFILE "$f"
  				else
   					echo "Error: Cannot read $f"
  				fi
			done
			echo "... new merlin-feed installed"
			opkg update
			echo "... opkg update executed"
		else
			echo "Error: something is wrong"
			exit 1
		fi
		echo "... new merlin-feed successfull installed"
	else
		echo "... image is not merlin, image is $reseller, exit installer"
		exit 1
	fi
else
	echo "... image has no file $IMAGE_VERSION, exit installer"
	exit 1
fi
exit 0
