#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
###########################################################################
# 
# File:            install_taloLoggerPi.py
#
# Author:          Olli Lammi (olammi@iki.fi)
#
# Version:         1.1h
#
# Date:            15.03.2020
#
# Description:     Script to install taloLoggerPi on empty Raspbian image.
#                  Supported distributions:
#                      Raspbian Wheezy (tested with 2015-05-05)
#                      Raspbian Jessie (tested with 2015-11-21)
#                      Raspbian Jessie Lite (tested with 2015-11-21)
#                      Raspbian Stretch Lite (tested with 2017-11-29)
#                      Raspbian Buster Lite (tested with 2019-09-26)
#
# Version history: ** 25.04.2014 v1.0c (Olli Lammi) **
#                  First version. 
#
#                  ** 28.12.2014 v1.1b (Olli Lammi) **
#                  Added talo user to www-data group and added  
#                  taloLoggerGraph image caching directory setup. 
#                  Added launcher for GPIO-support.
#
#                  ** 14.02.2015 v1.1c (Olli Lammi) **
#                  GPIO launcher changes. Added module python-oauth.  
#                  Added --test parameter to install test versions.
#
#                  ** 12.11.2015 v1.1d (Olli Lammi) **
#                  Fixed issue with Apache2 web configuration with 
#                  Raspbian Jessie.  
#
#                  ** 08.02.2016 v1.1e (Olli Lammi) **
#                  Added support for connecting to PostgreSQL databases.   
#                  Added support for persisting of VIRTUAL measurements 
#                  to file when logger is down.
#                  Fixed issues with daemontools starting and missing 
#                  /etc/inittab with Raspbian Jessie.
#                  Tested to work with Raspbian Jessie Lite.
#
#                  ** 22.01.2018 v1.1f (Olli Lammi) **
#                  Added support for Raspbian Stretch Lite.
#
#                  ** 23.11.2019 v1.1g (Olli Lammi) **
#                  Added support for Raspbian Buster Lite.
#
#                  ** 15.03.2020 v1.1h (Olli Lammi) **
#                  Added support for taloLogger MQTT data store - requires
#                  python-paho-mqtt package.
#
###########################################################################

# Imports

import sys,os,string
import urllib2, platform
import os.path
import time, subprocess
import re

###########################################################################

# Constants

VERSION = 'v1.1h'

BASEURL = 'http://olammi.iki.fi/sw/'
BASEURL_POSTFIX = '/current_release.txt'
BASEURL_TEST_POSTFIX = '/current_test_release.txt'

T_ROOT = '/home/talo/'
TL_ROOT = '/home/talo/bin/'
TLG_ROOT = '/home/talo/public_html/script/'

TOOLS_PRE = {}
TOOLS = {}
PACKAGES = []

TOOLS_DEFAULT = {'wget': '/usr/bin/wget', \
         'rm': '/bin/rm', \
         'mv': '/bin/mv', \
         'unzip': '/usr/bin/unzip', \
         'chown': '/bin/chown', \
         'chmod': '/bin/chmod', \
         'cp': '/bin/cp', \
         'apt-get': '/usr/bin/apt-get', \
         'dpkg': '/usr/bin/dpkg', \
         'useradd': '/usr/sbin/useradd', \
         'usermod': '/usr/sbin/usermod', \
         'id': '/usr/bin/id', \
         'tar': '/bin/tar', \
         'ln': '/bin/ln', \
         'insserv': '/sbin/insserv', \
         'mkdir': '/bin/mkdir', \
         'tar': '/bin/tar',
         'grep': '/bin/grep', \
         'echo': '/bin/echo', \
         'sed': '/bin/sed'}
TOOLS_DEFAULT_PRE = dict(TOOLS_DEFAULT)

PACKAGES_DEFAULT = ['daemontools', 'python-serial', 'python-imaging', 'python-mysqldb', \
            'python-sqlite', 'python-psycopg2', 'apache2', 'php5', \
            'php5-mysql', 'php5-sqlite', 'php5-pgsql', \
            'php5-gd', 'sqlite3', 'owfs', 'digitemp', 'rrdtool', 'i2c-tools', \
            'python-oauth', 'python-paho-mqtt' \
           ]

JESSIE_TOOLS = TOOLS_DEFAULT
JESSIE_TOOLS_PRE = TOOLS_DEFAULT
JESSIE_PACKAGES = PACKAGES_DEFAULT + ['daemontools-run']

STRETCH_TOOLS = dict(TOOLS_DEFAULT)
STRETCH_TOOLS_PRE = dict(TOOLS_DEFAULT_PRE)
STRETCH_TOOLS_PRE.pop('insserv')
STRETCH_PACKAGES = ['daemontools', 'python-serial', 'python-imaging', 'python-mysqldb', \
            'python-sqlite', 'python-psycopg2', 'apache2', 'php', \
            'php-mysql', 'php-sqlite3', 'php-pgsql', \
            'php-gd', 'sqlite3', 'owfs', 'digitemp', 'rrdtool', 'i2c-tools', \
            'python-oauth', 'daemontools-run', 'insserv', 'python-paho-mqtt' \
           ]

BUSTER_TOOLS = dict(TOOLS_DEFAULT)
BUSTER_TOOLS_PRE = dict(TOOLS_DEFAULT_PRE)
BUSTER_TOOLS_PRE.pop('insserv')
BUSTER_PACKAGES = ['daemontools', 'python-serial', 'python-pil:armhf', 'python-mysqldb', \
            'python-sqlite', 'python-psycopg2', 'apache2', 'php', \
            'php-mysql', 'php-sqlite3', 'php-pgsql', \
            'php-gd', 'sqlite3', 'owfs', 'digitemp', 'rrdtool', 'i2c-tools', \
            'python-oauth', 'daemontools-run', 'insserv', 'python-paho-mqtt' \
           ]

DISTRO_UNKNOWN = 'unknown'
DISTRO_RASPBIAN = 'RASPBIAN'
DISTRO_DEBIAN = 'DEBIAN'
DISTRO_WHEEZY = 'WHEEZY'
DISTRO_JESSIE = 'JESSIE'
DISTRO_STRETCH = 'STRETCH'
DISTRO_BUSTER = 'BUSTER'

SUID_LAUNCHER = TL_ROOT + 'raspberry_suid_python_launcher'

TL_SUIDABLE_SCRIPTS = [ 'modules/datasources/rpigpio/raspberryGpioThread.py' ]

###########################################################################

# Functions

def checkDistribution():
    distro = DISTRO_UNKNOWN
    distrover = DISTRO_UNKNOWN

    try:
        f = open('/etc/os-release', 'r')
        data = f.read()
        f.close()
    except:
        data = ''
    if len(data) > 0:
        data = data.upper()

        if DISTRO_BUSTER in data:
            distro = DISTRO_BUSTER
        elif DISTRO_RASPBIAN in data:
            distro = DISTRO_RASPBIAN
        elif DISTRO_DEBIAN in data:
            distro = DISTRO_DEBIAN

        global TOOLS
        global TOOLS_PRE
        global PACKAGES
        if DISTRO_WHEEZY in data:
            distrover = DISTRO_WHEEZY
            TOOLS = TOOLS_DEFAULT
            TOOLS_PRE = TOOLS_DEFAULT_PRE
            PACKAGES = PACKAGES_DEFAULT
        elif DISTRO_JESSIE in data:        
            distrover = DISTRO_JESSIE
            TOOLS = JESSIE_TOOLS
            TOOLS_PRE = JESSIE_TOOLS_PRE
            PACKAGES = JESSIE_PACKAGES
        elif DISTRO_STRETCH in data:
            distrover = DISTRO_STRETCH
            TOOLS = STRETCH_TOOLS
            TOOLS_PRE = STRETCH_TOOLS_PRE
            PACKAGES = STRETCH_PACKAGES
        elif DISTRO_BUSTER in data:
            distrover = DISTRO_BUSTER
            TOOLS = BUSTER_TOOLS
            TOOLS_PRE = BUSTER_TOOLS_PRE
            PACKAGES = BUSTER_PACKAGES
        else:
            # assume newest tools and packages for unknown release
            TOOLS = BUSTER_TOOLS
            TOOLS_PRE = BUSTER_TOOLS_PRE
            PACKAGES = BUSTER_PACKAGES
    
    return (distro, distrover)


def LocalVersion(fname, prefix):
    try:
        f = open(fname, 'r')
        data = f.read()
        f.close()
    except:
        data = ''
    if not data.upper().startswith(prefix.upper()):
        return ""
    return string.strip(data[len(prefix):])


def RetrieveCurrentVersion(url, piversion):
    res = ''
    try:
        USERAGENT = "taloLoggerPiInstall/" + piversion + " (Python/" + platform.python_version() + "; Sys/" + platform.platform() + ")"
        req = urllib2.Request(url)
        req.add_header("User-Agent", USERAGENT)
        f = urllib2.urlopen(req)
        res = f.readlines()
        f.close()
    except:
        return ""
    
    if len(res) <= 0:
        return ""
    
    res = string.strip(string.split(res[0], '\n')[0])
    return res


def RunCommand(cmd):
    stdout = ''
    try:
        sb = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        (stdout, stderr) = sb.communicate()
    except Exception, e:
        return ""
    return stdout

def ternary(cond, t, f):
    if cond:
        return t
    return f


####### main ##########################################################

def main():
    print "*********  taloLoggerPi - install_taloLoggerPi.py - " + VERSION + "  ********************"
    print
    
    # check that user is root
    if os.geteuid() != 0:
        print "ERROR: Install must be run as root. Exiting."
        sys.exit(1)
    
    TEST_VERSIONS = False
    if len(sys.argv) > 1:
        if sys.argv[1] == '--test':
            TEST_VERSIONS = True
    
    # check that this is a Raspbian system 
    (distro, distrover) = checkDistribution()
    if distro != DISTRO_RASPBIAN and distrover == DISTRO_UNKNOWN:
        print
        print "WARNING: this system seems not to be a known Raspbian installation."
        print "This installation script is intended for installing taloLoggerPi"
        print "on Raspbian systems. This install script might not work properly"
        print "on this system." 
        print
    
        temp = string.upper(string.strip(raw_input("Continue this install process (y/N)")))
        if not temp == 'Y':
            print "Exiting."
            sys.exit(0)

    
    # determining TOOLS
    shouldTerminate = 0
    for key in TOOLS_PRE.keys():
        tool = TOOLS_PRE[key]
        if not os.path.isfile(tool):
            tool = string.strip(RunCommand("which %s" % key))
            if (len(tool) <= 0 or not os.path.isfile(tool)):
                print "ERROR: Cannot find mandatory tool: %s" % key
                shouldTerminate = 1
            else:
                TOOLS_PRE[key] = tool
    if shouldTerminate:
        sys.exit(1)
        
    # check current versions
    
    print "Determining installed versions..."
    
    cur_tlpi = ''
    
    # check taloLoggerPi version
    cur_tlpi = LocalVersion('/home/talo/VERSION', 'taloLoggerPi')
    
    if len(cur_tlpi) > 0:
        print
        print "WARNING: taloLoggerPi version found already installed in this system (%s)." % (cur_tlpi, )
        print "Continuing this installation process may overwrite something. "
        print "Please make sure taloLogger is not running before continuing this install"
        print "process. Consider using upgrade_taloLogger.py to upgrade this system."
        print "(http://olammi.iki.fi/sw/taloLoggerPi/howto.php)"
        print
    
        temp = string.upper(string.strip(raw_input("Continue this install process (y/N)")))
        if not temp == 'Y':
            print "Exiting."
            sys.exit(0)

    print "Retrieving versions from the network..."
    
    url = BASEURL + 'taloLoggerPi/install_current_release.txt'
    net_tlpi_install = RetrieveCurrentVersion(url, VERSION)
    
    if len(net_tlpi_install) > 0 and net_tlpi_install > VERSION:
        print
        print "There is a newer version of this script install_taloLogger.py available."
        print "Current version %s, available version %s." % (VERSION, net_tlpi_install)
        print
    
        temp = string.upper(string.strip(raw_input("Proceed with this version (Y/n)")))
        if not (temp == '' or temp == 'Y'):
            print "Exiting."
            sys.exit(0)
    
    if TEST_VERSIONS:
        url = BASEURL + 'taloLogger' + BASEURL_TEST_POSTFIX
    else:    
        url = BASEURL + 'taloLogger' + BASEURL_POSTFIX
    net_tl = RetrieveCurrentVersion(url, VERSION)
    if TEST_VERSIONS:
        url = BASEURL + 'taloLoggerGraph' + BASEURL_TEST_POSTFIX
    else:    
        url = BASEURL + 'taloLoggerGraph' + BASEURL_POSTFIX
    net_tlg = RetrieveCurrentVersion(url, VERSION)

    print "This process will install:"
    print "    taloLoggerPi:    %s" % VERSION
    print "    taloLogger:      %s" % net_tl
    print "    taloLoggerGraph: %s" % net_tlg
    print     
    temp = string.upper(string.strip(raw_input("Proceed to install (Y/n)")))
    if not (temp == '' or temp == 'Y'):
        print "Exiting."
        sys.exit(0)
    
    print "Installing taloLoggerPi..."

    installed_packages = installPackages()

    installPostPackagesInstall(installed_packages)

    installUsers()

    tlWasStopped = stopTaloLogger()

    installDirs(VERSION)

    installTaloLogger(net_tl)

    installTaloLoggerGraph(net_tlg)
    
    installPostInstallFiles(VERSION, distrover)
    
    if tlWasStopped:
        startTaloLogger()

    print "Installed taloLoggerPi version %s." % VERSION


def getInstalledPackages():
    installed_packages = []
    cmd = TOOLS['dpkg'] + ' --get-selections'
    temp = RunCommand(cmd)
    if (len(temp) > 0):
        temp = string.split(temp, '\n')
        for rivi in temp:
            rivi = string.strip(rivi)
            if len(rivi) <= 0:
                continue
            regstr = "^(?P<package>.+)\s*install\s*$"
            
            try:
                result = re.match(regstr, rivi)
            except:
                continue
        
            if result != None:
                installed_packages.append(string.strip(result.group("package")))
                
    return installed_packages


def installPackages():
    print "Installing necessary apt-get -packages..."
    my_installed_packages = []
    installed_packages = getInstalledPackages()
    
    shouldUpdate = 0
    for package in PACKAGES:
        if not package in installed_packages:
            shouldUpdate = 1
            break
    if shouldUpdate:
        print "Updating apt-get database..."
        cmd = TOOLS['apt-get'] + ' update'
        os.system(cmd)

    for package in PACKAGES:
        if package in installed_packages:
            print "  Package %s already installed. Skipping..." % package
        else:
            print "  Installing package %s..." % package
            cmd = TOOLS['apt-get'] + ' -q -y install ' + package
            os.system(cmd)
            my_installed_packages.append(package)

    installed_packages = getInstalledPackages()
    
    shouldTerminate = 0
    for package in PACKAGES:
        if not package in installed_packages:
            shouldTerminate = 1
            print "  ERROR: Missing required package: %s" % package
    if shouldTerminate:
        print "Terminating install process due to missing packages."
        sys.exit(1)
        
    return my_installed_packages


def installPostPackagesInstall(installed_packages):
    print "Running post packages install tasks..."
    
    if "owfs" in installed_packages:
        # owfs-daemon-sammutukset
        os.system("/etc/init.d/owserver stop");
        os.system("/etc/init.d/owhttpd stop");
        os.system("/etc/init.d/owftpd stop");
        # owfs-daemon-disabloinnit
        os.system(TOOLS['insserv'] + ' -r /etc/init.d/owserver')
        os.system(TOOLS['insserv'] + ' -r /etc/init.d/owhttpd')
        os.system(TOOLS['insserv'] + ' -r /etc/init.d/owftpd')

    if ("daemontools" in installed_packages) and (not "daemontools-run" in installed_packages):    
        # daemontools: /etc/service
        if not os.path.isdir('/etc/service'):
            os.system('umask 022; ' + TOOLS['mkdir'] + ' /etc/service')
        
        # start svscanboot this time outside inittab
        cmd = '/usr/bin/svscanboot &'
        os.system(cmd)
        
    # add svscanboot to inittab if it does not exist
    cmd = TOOLS['grep'] + ' -q "/usr/bin/svscanboot" /etc/inittab || echo "SV:12345:respawn:/usr/bin/svscanboot" >> /etc/inittab'
    os.system(cmd)

        
    if "apache2" in installed_packages:
        cmd = TOOLS['cp'] + ' /etc/apache2/apache2.conf /etc/apache2/apache2.conf_original'
        os.system(cmd)
        # alter apache server configuration
        cmd = TOOLS['sed'] + ' -i \'/<IfModule\\smpm_prefork_module>/,/<\\/IfModule>/s/StartServers\\s.*/StartServers\\t1/\' /etc/apache2/apache2.conf'
        os.system(cmd)
        cmd = TOOLS['sed'] + ' -i \'/<IfModule\\smpm_prefork_module>/,/<\\/IfModule>/s/MinSpareServers\\s.*/MinSpareServers\\t1/\' /etc/apache2/apache2.conf'
        os.system(cmd)
        cmd = TOOLS['sed'] + ' -i \'/<IfModule\\smpm_prefork_module>/,/<\\/IfModule>/s/MaxSpareServers\\s.*/MaxSpareServers\\t5/\' /etc/apache2/apache2.conf'
        os.system(cmd)


def installUsers():
    cmd = TOOLS['id'] + ' -u talo'
    if os.system(cmd) == 0:
        print "User talo already exists."
    else:
        print "Adding user talo..."
        cmd = TOOLS['useradd'] + ' -m -U talo'
        os.system(cmd)
        cmd = TOOLS['id'] + ' -u talo'
        if os.system(cmd) == 0:
            print "Added user talo."
        else:
            print "Cannot add user talo. Exiting."
            sys.exit(1)
    
    print "Setting user talo groups..."
    cmd = TOOLS['usermod'] + ' --groups uucp,dialout,video,www-data talo'
    os.system(cmd)


def installDirs(version):
    print "Installing user talo home folder..."

    packname = 'taloLoggerPi_home_' + string.replace(version, '.', '') + '.tgz'
    tmpfile = '/tmp/' + packname

    # retrieve new package
    if os.path.isfile(tmpfile):
        print "Removing old temporary release package."
        os.system(TOOLS['rm'] + ' -f ' + tmpfile)
    cmd = TOOLS['wget'] + ' -O ' + tmpfile + ' '
    cmd = cmd + BASEURL + 'taloLoggerPi/' + packname
    print "Retrieving release package from network." 
    os.system(cmd)

    if not os.path.isfile(tmpfile) or os.path.getsize(tmpfile) <= 0:
        if os.path.isfile(tmpfile):
            os.system(TOOLS['rm'] + ' -f ' + tmpfile)
        print "ERROR: Cannot retrieve taloLoggerPi talo home folder release package. Exiting."
        sys.exit(1)

    bu_file = 'talo_home_backup_' + time.strftime('%Y%m%d%H%M%S') + '.tgz'
    print "Generating backup of old talo home folder to %s%s..." % (T_ROOT, bu_file)
    os.system(TOOLS['rm'] + ' -rf ' + T_ROOT + bu_file)
    os.system(TOOLS['rm'] + ' -rf ' + '/tmp/' + bu_file)
    os.system(TOOLS['tar'] + ' czf /tmp/' + bu_file + ' ' + T_ROOT)
    os.system(TOOLS['rm'] + ' -rf ' + T_ROOT + '*')
    os.system(TOOLS['mv'] + ' /tmp/' + bu_file + ' ' + T_ROOT + bu_file)

    print "Unpacking release package."
    cmd = 'umask 022; ' + TOOLS['tar'] + ' -x -z -f ' + tmpfile + ' -C ' + T_ROOT
    os.system(cmd)
    print "Adjusting file access rights."
    os.system(TOOLS['chown'] + ' -R talo:talo ' + T_ROOT + '*')

    TLGCACHE = T_ROOT + 'public_html/tlgcache'
    if os.path.isdir(TLGCACHE):
        os.system(TOOLS['chown'] + ' talo:www-data ' + TLGCACHE)
        os.system(TOOLS['chmod'] + ' 775 ' + TLGCACHE)
        os.system(TOOLS['chmod'] + ' g+s ' + TLGCACHE)

    if os.path.isfile(SUID_LAUNCHER):
        os.system(TOOLS['chown'] + ' root:talo ' + SUID_LAUNCHER)
        os.system(TOOLS['chmod'] + ' 750 ' + SUID_LAUNCHER)
        os.system(TOOLS['chmod'] + ' u+s ' + SUID_LAUNCHER)
        
    if os.path.isfile(tmpfile):
        print "Removing temporary release package."
        os.system(TOOLS['rm'] + ' -f ' + tmpfile)

    print "Installed user talo home folder."
    print    


def stopTaloLogger():
    wasStopped = False
    if os.path.isfile('/usr/bin/svstat') and os.path.islink('/etc/service/taloLogger'):
        temp = RunCommand('/usr/bin/svstat /etc/service/taloLogger')
        try:
            temp = string.strip(string.split(string.strip(string.split(temp, ':')[1]), ' ')[0])
        except:
            temp = ''
        if temp.upper() == 'UP':
            wasStopped = True
    
            print "Stopping taloLogger."
            os.system('/usr/bin/svc -d /etc/service/taloLogger')
            time.sleep(4)
    return wasStopped


def startTaloLogger():
    if os.path.isfile('/usr/bin/svc') and os.path.islink('/etc/service/taloLogger'):
        print "Starting taloLogger."
        os.system('/usr/bin/svc -u /etc/service/taloLogger')


def installTaloLogger(version):
    print "Installing taloLogger version %s..." % version

    packname = 'taloLogger_' + string.replace(version, '.', '') + '.zip'
    tmpfile = '/tmp/' + packname

    # retrieve new package
    if os.path.isfile(tmpfile):
        print "Removing old temporary release package."
        os.system(TOOLS['rm'] + ' -f ' + tmpfile)
    cmd = TOOLS['wget'] + ' -O ' + tmpfile + ' '
    cmd = cmd + BASEURL + 'taloLogger/' + packname
    print "Retrieving release package from network." 
    os.system(cmd)

    if not os.path.isfile(tmpfile) or os.path.getsize(tmpfile) <= 0:
        if os.path.isfile(tmpfile):
            os.system(TOOLS['rm'] + ' -f ' + tmpfile)
        print "ERROR: Cannot retrieve taloLogger release package. Exiting."
        sys.exit(1)

    if os.path.isdir(TL_ROOT + 'taloLogger'):
        print "Moving old taloLogger installation folder with name taloLogger_old"
        os.system(TOOLS['rm'] + ' -rf ' + TL_ROOT + 'taloLogger_old')
        os.system(TOOLS['mv'] + ' ' + TL_ROOT + 'taloLogger ' + TL_ROOT + 'taloLogger_old')

    print "Unpacking release package."
    cmd = 'umask 022; ' + TOOLS['unzip'] + ' -d ' + TL_ROOT + ' ' + tmpfile
    os.system(cmd)
    print "Adjusting file access rights."
    os.system(TOOLS['chown'] + ' -R talo:talo ' + TL_ROOT + 'taloLogger')
    os.system(TOOLS['chmod'] + ' 755 ' + TL_ROOT + 'taloLogger')

    # manage suidable tool python script file rights
    for fn in TL_SUIDABLE_SCRIPTS:
        tfn = TL_ROOT + 'taloLogger/' + fn
        if os.path.isfile(tfn):
            os.system(TOOLS['chown'] + ' root:talo ' + tfn)
            os.system(TOOLS['chmod'] + ' 754 ' + tfn)
            os.system(TOOLS['chmod'] + ' u+s ' + tfn)

    if os.path.isfile(tmpfile):
        print "Removing temporary release package."
        os.system(TOOLS['rm'] + ' -f ' + tmpfile)

    cmd = TOOLS['cp'] + ' ' + TL_ROOT + 'taloLogger/taloLogger.conf'
    cmd = cmd + ' /home/talo/etc/taloLogger.conf_original'
    os.system(cmd)

    print "Installed taloLogger version %s." % version
    print


def installTaloLoggerGraph(version):
    print "Installing taloLoggerGraph version %s..." % version

    packname = 'taloLoggerGraph_' + string.replace(version, '.', '') + '.zip'
    tmpfile = '/tmp/' + packname

    # retrieve new package
    if os.path.isfile(tmpfile):
        print "Removing old temporary release package."
        os.system(TOOLS['rm'] + ' -f ' + tmpfile)
    cmd = TOOLS['wget'] + ' -O ' + tmpfile + ' '
    cmd = cmd + BASEURL + 'taloLoggerGraph/' + packname
    print "Retrieving release package from network." 
    os.system(cmd)

    if not os.path.isfile(tmpfile) or os.path.getsize(tmpfile) <= 0:
        if os.path.isfile(tmpfile):
            os.system(TOOLS['rm'] + ' -f ' + tmpfile)
        print "ERROR: Cannot retrieve taloLoggerGraph release package. Exiting."
        sys.exit(1)

    if os.path.isdir(TLG_ROOT + 'taloLoggerGraph'):
        print "Moving old taloLoggerGraph installation folder with name taloLoggerGraph_old"
        os.system(TOOLS['rm'] + ' -rf ' + TLG_ROOT + 'taloLoggerGraph_old')
        os.system(TOOLS['mv'] + ' ' + TLG_ROOT + 'taloLoggerGraph ' + TLG_ROOT + 'taloLoggerGraph_old')

    print "Unpacking release package."
    cmd = 'umask 022; ' + TOOLS['unzip'] + ' -d ' + TLG_ROOT + ' ' + tmpfile
    os.system(cmd)
    print "Adjusting file access rights."
    os.system(TOOLS['chown'] + ' -R talo:talo ' + TLG_ROOT + 'taloLoggerGraph')
    os.system(TOOLS['chmod'] + ' 755 ' + TLG_ROOT + 'taloLoggerGraph')

    if os.path.isfile(tmpfile):
        print "Removing temporary release package."
        os.system(TOOLS['rm'] + ' -f ' + tmpfile)

    cmd = TOOLS['cp'] + ' ' + TLG_ROOT + 'taloLoggerGraph/taloLoggerGraph.conf'
    cmd = cmd + ' ' + T_ROOT + 'public_html/taloLoggerGraph.conf_original'
    os.system(cmd)

    print "Installed taloLoggerGraph version %s." % version
    print
    
    
def substituteFile(fname, substdict):
    for key in substdict.keys():
        vkey = string.replace(key, '$', '\\$')
        vkey = string.replace(vkey, '%', '\\%')
        val = substdict[key]
        val = string.replace(val, '/', '\\/')
        cmd = TOOLS['sed'] + ' -i \'s/' + vkey + '/' + val + '/g\' ' + fname
        os.system(cmd)


def installPostInstallFiles(version, distrover):
    print "Running post install tasks..."
        
    # daemontools: /etc/service, talologger-linkki
    if not os.path.islink('/etc/service/taloLogger'):
        os.system(TOOLS['ln'] + ' -s ' + T_ROOT + 'service/taloLogger /etc/service/taloLogger')

    # apache2: default.d
    if not os.path.isdir('/etc/apache2/default.d'):
        os.system('umask 002; ' + TOOLS['mkdir'] + ' /etc/apache2/default.d')
    if not os.path.isdir('/etc/apache2/default.d'):
        print "ERROR: Cannot find or create apache2 configuration directory: /etc/apache2/default.d. Terminating."
        sys.exit(1)

    # default for newest
    WWW_ROOT = '/var/www/html'
    DEFAULT_FILE = '/etc/apache2/sites-available/000-default.conf'

    if distrover == DISTRO_WHEEZY:
        WWW_ROOT = '/var/www'
        DEFAULT_FILE = '/etc/apache2/sites-available/default'

    FILES_TO_SUBSTITUTE = [T_ROOT + 'etc/talo_apache2.conf', T_ROOT + 'public_html/taloLoggerGraph.conf']
    SUBSTDICT = {'$%_WWWROOT_%$': WWW_ROOT}
    for fn in FILES_TO_SUBSTITUTE:
        substituteFile(fn, SUBSTDICT)
    
    FOUND_DEFAULT = None
    if os.path.isfile(DEFAULT_FILE):
        # add Include default.d/ to default web config if it does not exist
        cmd = TOOLS['grep'] + ' -q "Include default.d/" ' + DEFAULT_FILE + ' || '
        cmd = cmd + TOOLS['sed'] + ' -i \'s/<\\/VirtualHost>/\\n        Include default.d\\/\\n<\\/VirtualHost>/\' ' + DEFAULT_FILE
        os.system(cmd)
        FOUND_DEFAULT = DEFAULT_FILE

    if not FOUND_DEFAULT:
        print "ERROR: Cannot find default web configuration file: %s " % DEFAULT_FILE
        print "       taloLoggerPi web interface will not work properly!"

    # apache2: default.d-linkki        
    if not os.path.islink('/etc/apache2/default.d/talo'):
        os.system(TOOLS['ln'] + ' -s ' + T_ROOT + 'etc/talo_apache2.conf /etc/apache2/default.d/talo')

    if not os.path.islink(WWW_ROOT + '/talo'):
        os.system(TOOLS['ln'] + ' -s ' + T_ROOT + 'public_html ' + WWW_ROOT + '/talo')
    if not os.path.islink(WWW_ROOT + '/index.html'):
        if os.path.isfile(WWW_ROOT + '/index.html'):
            os.system(TOOLS['mv'] + ' ' + WWW_ROOT + '/index.html ' + WWW_ROOT + '/index.html_original')
        os.system(TOOLS['ln'] + ' -s ' + T_ROOT + 'public_html/index_var_www.html ' + WWW_ROOT + '/index.html')


    # restart apache2
    print "Restarting apache2..."
    cmd = "/etc/init.d/apache2 restart"
    os.system(cmd)
    
    # write VERSION file
    try:
        f = open(T_ROOT + 'VERSION', 'w')
        f.write('taloLoggerPi ' + version + '\n')
        f.close()
        os.system(TOOLS['chown'] + ' talo:talo ' + T_ROOT + 'VERSION')
        os.system(TOOLS['chmod'] + ' 644 ' + T_ROOT + 'VERSION')
    except:
        print "ERROR: Cannot write version file: %sVERSION. Terminating." % T_ROOT
        sys.exit(1)


###########################################################################

if __name__ == "__main__":
  main()
