#!/bin/bash
#
#Copyright 2012 -2017 CurlyMo & mkreisl <development@xbian.org>
#
#This file is part of XBian - XBMC on the Raspberry Pi.
#
#XBian is free software: you can redistribute it and/or modify it under the
#terms of the GNU General Public License as published by the Free Software
#Foundation, either version 3 of the License, or (at your option) any later
#version.
#
#XBian is distributed in the hope that it will be useful, but WITHOUT ANY
#WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
#FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
#details.
#
#You should have received a copy of the GNU General Public License along
#with XBian. If not, see <http://www.gnu.org/licenses/>

# Get the current hostname
#  $1 [Container] Hostname
# Returns
#  $HOSTNAME [String]
function getCurrentHostnameFn() {
	HOSTNAME=$(cat /etc/hostname);
}

# Get the current hostname
#  $1 [String] New hostname
#  $2 [String] Old hostname
# Returns
#  * [Integer]
#  - 1: Success
#  - 0: Failed
function setHostnameFn() {
	echo "$1" > /etc/hostname
	hostname -F /etc/hostname
	sed -i "s/$2 /$1 /g" /etc/hosts
	sed -i "s/$2\t/$1\t/g" /etc/hosts
	sed -i "s/$2\./$1\./g" /etc/hosts
	sed -i "s/$2\$/$1/g" /etc/hosts
	mkdir -p /run/xbian-config
	[ -d /home/xbian/.kodi ] && XBMC_KODI_DIR="/home/xbian/.kodi" || XBMC_KODI_DIR="/home/xbian/.xbmc"
	for GUISETTINGSXML in $(find $XBMC_KODI_DIR -name guisettings.xml); do
		echo "sed -i 's%<devicename.*>.*</devicename>%<devicename>$1</devicename>%' $GUISETTINGSXML" >> /run/xbian-config/xbmc-hostname
	done
	for PERIPHERALDATA in $(find $XBMC_KODI_DIR -type d -name peripheral_data); do
		echo "sed -i 's%<setting id=\"device_name\" value=\".*\" />%<setting id=\"device_name\" value=\"$1\" />%' $PERIPHERALDATA/*" >> /run/xbian-config/xbmc-hostname
	done
	if pgrep xbmc.bin >/dev/null || pgrep kodi.bin >/dev/null; then
	    cat /run/xbian-config/xbmc-hostname >> /run/xbian-config/xbmc-changesettings.sh
	else
	    sh /run/xbian-config/xbmc-hostname
	fi
	rm /run/xbian-config/xbmc-hostname
	if [ $(hostname) == $1 ]; then
		return 1;
	else
		return 0;
	fi
}
