#!/bin/bash
#----------------------------------------------------------------------------
# Copyright (c) 2001-2016 The Eisfair Team <team@eisfair.org>
#
# This program 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 2 of the License, or
# (at your option) any later version.
#----------------------------------------------------------------------------
# usage: edit [--apply|--apply-stopstart] file
#        edit [--apply|--apply-stopstart] package message
#----------------------------------------------------------------------------

get_date()
{
    old_ifs="$IFS"
    IFS=.
    set $1
    eval echo \$$#
    IFS="$old_ifs"
}

# backup config
backup_config()
{
    local package=$1
    local file=$2
    local stamp=$(date +%Y-%m-%d-%H-%M-%S)
    local fmask='*[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]-[0-9][0-9]-[0-9][0-9]-[0-9][0-9]'
    local _ccf_max_backup=10    
    # do the backup
    if [ -f $file ] ; then
        cp -p $file /etc/backup.d/$package.$stamp
        chmod og-rw /etc/backup.d/$package.$stamp
        logger "Configuration file was saved as /etc/backup.d/$package.$stamp"
    else
        logger "File $file not found - no backup done"
    fi
    # check if files have to be deleted
    # count files
    fcount=$(find /etc/backup.d -maxdepth 1 -type f -name "${package}.${fmask}" 2>/dev/null | wc -l)

    # check number of files
    if [ "$fcount" -gt "${_ccf_max_backup}" ] ; then
        # number of files to remove
        rmcount=`expr $fcount - ${_ccf_max_backup}`
        count=0
        # find files in sorted order
        {
            for FNAME in `find /etc/backup.d -maxdepth 1 -type f -name "${package}.${fmask}"`
            do
                # extract timestamp
                FDATE=$(get_date ${FNAME})
                # add timestamp as second field to in-transit output
                echo "${FNAME}:${FDATE}"
            done
        } | sort -t: -k2 | while read line
        do
            # remove obsolete files
            if [ "$count" -lt "$rmcount" ] ; then
                # extract filename from line
                file=$(echo ${line} | cut -d: -f1)
                rm $file
                count=$((count + 1))
            else
                break
            fi
        done
        logger "Backup directory contained $fcount files for package $package ($rmcount removed)."
    fi
}

apply=''
case "$1" in
    --apply|-apply)
        apply='restart'
        shift
    ;;
    --apply-stopstart|-apply-stopstart)
        apply='stopstart'
        shift
    ;;
esac

if [ $# -eq 1 ] ; then
    package=$(basename $1)
else
    package="$1"
fi


exitval=0

# edit first package...
current_package=$(echo $package | sed -e 's/ .*$//g')

if [ -f /etc/config.d/$current_package ] ; then
    if ! /var/install/bin/edit-conf.cui --check /etc/config.d/$current_package
    then
        /var/install/bin/ask.cui --err "The configuration of this package can't be opened" 
        exit 1
    fi

    old_umask=`umask`
    umask 077       # do not allow anybody to read anything
                    # config or logfile may contain secret passwords

    # delete old tmpfile first, if exists ;-)
    rm -f /tmp/edit-${current_package}-*

    # create tmpfile name, do not change this name,
    # many programs get the old config settings from it,
    # to compare the value
    tmp_edit_file=/tmp/edit-${current_package}-$$

    # copy to tmpfile
    cp -p /etc/config.d/$current_package ${tmp_edit_file}

    # run editor
    if ! /var/install/bin/edit-conf.cui -l /var/log/edit-conf.log /etc/config.d/$current_package
    then
        cp -p ${tmp_edit_file} /etc/config.d/$current_package 
        rm -f ${tmp_edit_file}
        exit 0
    fi
    # config_shlib has owne handling
    umask $old_umask

    if ! diff ${tmp_edit_file} /etc/config.d/$current_package >/dev/null
    then
        backup_config $current_package ${tmp_edit_file}
    fi
fi

# call apply-script if exists
apply_script()
{
    if [ -f /var/install/config.d/${1}.sh ] ; then
        sh /var/install/config.d/${1}.sh
    else
        return 0
    fi
    rm -f ${tmp_edit_file}
}

# can start package
can_start()
{
    local startvar
    local start
    # read configuration file
    . /etc/config.d/${1}
    # change also '-' to '_', many packages use a '-' in the name,
    # like package-dev and START_PACKAGE-DEV does not work :-(
    startvar=$(echo START_${1} | tr 'a-z' 'A-Z' | tr '-' '_')
    eval start='$'${startvar}
    if [ -n "$start" ] ; then
        test "${start}" = "yes"
    else
        # if the START_* varname not the package name (vsftpd with START_FTP)
        startvar=$(grep "^START_.*" /etc/config.d/${1} |  sed 's/=.*/\1/')
        eval start='$'${startvar}
        test "${start}" = "yes"
    fi
}

if [ -n "$apply" ] ; then
    if [ "$package" = "base" -o "$package" = "environment" ] ; then
        apply_script $package
    else
        if /var/install/bin/ask.cui "Activate configuration now?" ; then
            # activate changes
            for current_package in $package
            do
                if [ -f /etc/init.d/$current_package ] ; then
                    if [ "$apply" = "restart" ] ; then
                        if  apply_script $current_package &&
                            can_start    $current_package
                        then
                            # restart package
                            /sbin/rc-service -i -q $current_package restart
                            /sbin/rc-update -q add $current_package default >/dev/null 2>&1
                        else
                            # stop package
                            /sbin/rc-service -i -q $current_package stop
                            [ /sbin/rc-service -e $current_package ] && /sbin/rc-update -q del $current_package
                        fi
                    elif [ "$apply" = "stopstart" ] ; then
                        init_script $current_package stop
                        if  apply_script $current_package &&
                            can_start    $current_package
                        then
                            /sbin/rc-service -i -q $current_package start
                            /sbin/rc-update -q add $current_package default >/dev/null 2>&1
                        else
                            [ /sbin/rc-service -e $current_package ] && /sbin/rc-update -q del $current_package
                        fi
                    fi
                else
                    apply_script "$current_package"
                fi
            done
            sleep 1
        fi
    fi
fi

# do it twice ;-)
rm -f ${tmp_edit_file}

# create alpine LBU backup if system run from tmpfs
rootfs=$(grep "/ " /proc/mounts)
case "$rootfs" in
    tmpfs*)
	if ! egrep -q '^LBU_MEDIA=' /etc/lbu/lbu.conf
	then
	    /sbin/setup-lbu -q mmcblk0p1
	fi
	if [ ! -d /media/mmcblk0p1/cache ]
	then
	    mkdir -p /media/mmcblk0p1/cache
	    /sbin/setup-apkcache /media/mmcblk0p1/cache
	fi
	if [ -f /media/mmcblk0p1/$(hostname).apkovl.tar.gz ]
        then
            lbu ci
        else
            lbu ci -d
        fi
        ;;
esac

exit 0
