#!/bin/sh

PACKAGE=landscape-client

CONFIGFILE=/etc/landscape/client.conf
set -e
. /usr/share/debconf/confmodule

var_in_file() {
    var="$1"
    file="$2"
    line=$(grep "^$var\s*=\s*" "$file" 2>/dev/null || true)
    echo "$line"
}

get_var_from_file() {
    var="$1"
    file="$2"
    val=$(grep "^$var\s*=\s*" "$file" 2>/dev/null | tail -n1 | sed "s/^.*=\s*//")
    echo "$val"
}

update_var() {
    var="$1"
    file="$2"
    line=$(var_in_file $var $file)
    if [ -n "$line" ]; then
        val=$(get_var_from_file $var $file)
        # Store value from config file in debconf.
        db_set $PACKAGE/$var $val
    fi
}

# Load config file, if it exists.
if [ -e $CONFIGFILE ]; then
    # Replace old registration_password to registration_key
    sed -i -r 's/^registration_password[[:blank:]]*=/registration_key =/' $CONFIGFILE
    # Config file is "ini" type, not shell, so we cannot source it
    # If a setting is defined in the config file, update it in debconf
    # db.
    update_var "computer_title" "$CONFIGFILE"
    update_var "account_name" "$CONFIGFILE"
    update_var "registration_key" "$CONFIGFILE"
    update_var "url" "$CONFIGFILE"
    update_var "exchange_interval" "$CONFIGFILE"
    update_var "urgent_exchange_interval" "$CONFIGFILE"
    update_var "ping_url" "$CONFIGFILE"
    update_var "ping_interval" "$CONFIGFILE"
    update_var "http_proxy" "$CONFIGFILE"
    update_var "https_proxy" "$CONFIGFILE"
    update_var "tags" "$CONFIGFILE"
fi

# Ask questions.
# Do debconf configuration
db_get $PACKAGE/register_system
if [ "$RET" = true ]; then
    priority=high
else
    priority=medium
fi
db_input "$priority" $PACKAGE/computer_title || true
db_input "$priority" $PACKAGE/account_name || true
db_input "$priority" $PACKAGE/registration_key || true

db_go || true
