#! /bin/bash
#
# MoodleBox init script
# Created for MoodleBox 4.5.0, 2022-11-29
#
# This script is part of MoodleBox
# Copyright (C) 2022 onwards Nicolas Martignoni
#
# This script is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This script  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 Affero General Public License
# along with this script.  If not, see <https://www.gnu.org/licenses/>.

### BEGIN INIT INFO
# Provides: fix_hostname_once
# Required-Start:
# Required-Stop:
# Default-Start: 3
# Default-Stop:
# Short-Description: Starts fix_hostname_once to fix hostname
# Description:
### END INIT INFO

. /lib/lsb/init-functions

SCRIPTPATH="$(cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P)"
SCRIPTNAME="$(basename $0)"

case "$1" in
  start)
    log_daemon_msg "Fixing hostname" &&
    NEW_HOSTNAME=$(hostnamectl --static) &&
    CURRENT_HOSTNAME="moodlebox" &&
    sed -ri "s/(((25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])\.?\b){4})\s+${CURRENT_HOSTNAME}/\1\t${NEW_HOSTNAME}/g" /etc/hosts &&
    update-rc.d ${SCRIPTNAME} remove &&
    rm -f ${SCRIPTPATH}/${SCRIPTNAME} &&
    log_end_msg $?
    ;;
  *)
    echo "Usage: $0 start" >&2
    exit 3
    ;;
esac
