#!/bin/bash

# set alternative root path with -r option (must be first option!)
if [ "$1" = "-r" ]; then
    ROOT="${2%/}"
    shift 2
else
    ROOT=
fi

# The main resource file
RCMAIN="$ROOT"/usr/share/resources/default/init/main

net_conf_def="$ROOT"/etc/network/interfaces.spxsave
ntpdate_conf="$ROOT"/etc/default/ntpdate
ntpdate_conf_def="$ROOT"/etc/default/ntpdate.spxsave
timezone="$ROOT"/etc/timezone
localtime="$ROOT"/etc/localtime
php_timezone="$ROOT"/etc/php/conf.d/timezone.ini

# Load resources
[ -f "$RCMAIN" ] && . "$RCMAIN"

# Load the identifiers
[ -f /etc/spinetix/identifiers ] && . /etc/spinetix/identifiers

# Load the common part of variables and function definitions
. "$ROOT"/etc/spinetix/spxsysconf-common

function net_config_default()
{
    # This function cannot leave a half written file, it must be atomic
    local file="$1"
    local tmp="$(cptemp "$net_conf_def")" || return 1

    [ -n "$file" ] || file="$net_conf"

    net_config_iface_dhcp "$SPX_MAIN_IFACE_NAME" "$tmp" || return
    "$fsync" "$tmp" && mv -f -- "$tmp" "$file" || return

    return 0
}

function net_config_iface()
{
    local ret method params tmp dnstmp
    local iface="$1"
    local conf="$2"

    tmp="$(cptemp "$net_conf")"
    if [ $? -ne 0 ]; then
        echo "ERROR: failed editing file in spxsysconf (no temp)" >&2
        return 1
    fi

    if ! config_clean "$tmp"; then
        echo "ERROR: failed editing file in spxsysconf (cannot clean)" >&2
        rm -f -- "$tmp"
        return 1
    fi

    method="${conf%%=*}"
    params="${conf#*=}"
    [ "$params" != "$conf" ] || params=

    # global variable to pass back modifications to config string, if any
    NETCONFIG=

    case "$method" in
        dhcp)
            net_config_iface_dhcp "$iface" "$tmp"
            ret=$?
            ;;
        static)
            dnstmp="$(cptemp "$static_resolv_conf")" && cat /dev/null > "$dnstmp"
            if [ $? -ne 0 ]; then
                [ -n "$dnstmp" ] && rm -f -- "$dnstmp"
                ret=1
            else
                net_config_iface_static "$iface" "$params" "$tmp" "$dnstmp"
                ret=$?
            fi
            ;;
        *)
            echo "ERROR: unknown network config method '$method'" >&2
            ret=1
    esac

    if [ $ret -eq 0 ]; then
        [ -n "$NETCONFIG" ] || NETCONFIG="$conf"
        if ! failsafe-data set network "$NETCONFIG"; then
            echo "WARNING: failed saving network configuration for recovery console"
        fi
        mv -f -- "$tmp" "$net_conf" || ret=1
        [ -n "$dnstmp" ] && mv -f -- "$dnstmp" "$static_resolv_conf" || ret=1
    fi

    [ -f "$tmp" ] && rm -f -- "$tmp"
    [ -n "$dnstmp" -a -f "$dnstmp" ] && rm -f -- "$dnstmp"

    return $ret
}

function ntpdate_set_server()
{
    if [ ! -f "$ntpdate_conf" ]; then
        echo "WARNING: no default ntpdate configuration" >&2
        return
    fi
    # transfer the factory default config to ntpdate's config
    . "$ntpdate_conf_def"
    sed_inplace -e "s/^[ \t]*NTPSERVERS=.*$/NTPSERVERS='$NTPSERVERS'/" "$ntpdate_conf"
}

function tz_set_default()
{
    if [ -n "$rc_default_tz" ]; then
        ln -sf ../usr/share/zoneinfo/"$rc_default_tz" "$localtime"
        if [ ! -f "$localtime" ]; then
            echo "ERROR: invalid default timezone" >&2
            rm -f "$localtime" "$timezone"
            return 1
        fi
        echo "$rc_default_tz" > "$timezone"
        return 0
    else
        rm -f "$localtime" "$timezone"
        echo "WARNING: no default timezone" >&2
        return 0
    fi
}

function php_tz_set_to_sys()
{
    local tz
    tz="$(readlink "$localtime" | sed -e 's|.*/zoneinfo/||')"
    if [ -z "$tz" ]; then
        echo "WARNING: no default timezone" >&2
        return 0
    fi
    # Replace the (possibly commented out) date.timezone setting by the timezone
    sed_inplace -e '/^[[:space:];]*date\.timezone[[:space:]]*=/s|^[[:space:];]*\(date\.timezone[[:space:]]*=\).*|\1 "'"$tz"'"|' "$php_timezone"
}

#
# Main
#

case "$1" in
    config|config-reset|upgrade)
        # NOTE: "config" runs in a cross-target environment, so it cannot refer
        # any data from the target system
        if [ "$1" = "config-reset" ]; then
            # Do whatever is required to prepare for the config steps
            # below, removing any configuration which should not be
            # present to perform the "config" below.
            net_config_default
        fi
        if [ "$1" = "config" -o "$1" = "config-reset" ]; then
            # These apply only to initial config, since user may change them
            ntpdate_set_server
            tz_set_default
        fi
        # The ones below also apply to upgrade
        php_tz_set_to_sys
        ;;
    dhcp)
        config_clean "$net_conf"
        net_config_iface_dhcp "$SPX_MAIN_IFACE_NAME"
        ;;
    net)
        net_config_iface "$SPX_MAIN_IFACE_NAME" "$2"
        ;;
    net-default)
        net_config_default
        ;;
    *)
        echo "Usage: $0 {config|config-reset|upgrade|dhcp|net <config>|net-init}"
esac
