#!/bin/sh
set -e

# summary of how this script can be called:
#        * <postinst> `configure' <most-recently-configured-version>
#        * <old-postinst> `abort-upgrade' <new version>
#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
#          <new-version>
#        * <postinst> `abort-remove'
#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
#          <failed-install-package> <version> `removing'
#          <conflicting-package> <version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package


# Blog configuration and initial content are writtent by functions which are
# called from the main script, mostly to avoid polluting it with indentation
# violation produced by the uses of `cat << EOF`.


# Generate Apache configuration, managed by ucf
# No dynamic part yet, but there may be, so better use ucf from the beginning
write_apache2_conf()
{
    apache2_conf="$(tempfile)"
    cat >> "$apache2_conf" <<- EOF
	# apache2 configuration file for pluxml
	Alias /pluxml /usr/share/pluxml
	
	<Directory /usr/share/pluxml>
	    <IfModule mod_rewrite.c>
	            # Uncomment to implement server-side URL rewriting
	            #RewriteEngine on
	            #RewriteBase /pluxml
	            #RewriteRule ^config.php    - [L]
	            #RewriteRule ^core/         - [L]
	            #RewriteRule ^data/         - [L]
	            #RewriteRule ^feed.php      - [L]
	            #RewriteRule ^index.php     - [L]
	            #RewriteRule ^plugins/      - [L]
	            #RewriteRule ^sitemap.php   - [L]
	            #RewriteRule ^themes/       - [L]
	            #RewriteRule ^update/       - [L]
	            #RewriteRule ^feed/(.*)$    feed.php?$1  [L]
	            #RewriteRule ^(.*)$         index.php?$1 [L]
	    </IfModule>
	</Directory>
	
	<Directory /var/lib/pluxml/data>
	        Options -Indexes
	</Directory>
	<DirectoryMatch "^/var/lib/pluxml/data/(articles|commentaires|configuration|statiques)">
	        Require all denied
	</DirectoryMatch>
	EOF
    # Install file with ucf
    ucf --debconf-ok "$apache2_conf" /etc/pluxml/apache2.conf
    ucfr pluxml /etc/pluxml/apache2.conf
    # Remove temporary file
    rm -f "$apache2_conf"
}


# Enable apache2 configuration
enable_apache2_conf()
{
    if [ -d /etc/apache2/conf-available -a ! -e /etc/apache2/conf-available/pluxml.conf ]
    then
        ln -s /etc/pluxml/apache2.conf /etc/apache2/conf-available/pluxml.conf
        if [ -e /usr/share/apache2/apache2-maintscript-helper ]
        then
            . /usr/share/apache2/apache2-maintscript-helper
            apache2_invoke enconf pluxml
        fi
    fi
}


# Reload apache2
reload_apache2()
{
    # Nothing, since `apache2_invoke enconf` already did what had to be done
    :
}


# Write lighttpd configuration, managed by ucf
# No dynamic part yet, but there may be, so better use ucf from the beginning
write_lighttpd_conf()
{
    lighttpd_conf="$(tempfile)"
    cat >> "$lighttpd_conf" <<- EOF
	# lighttpd configuration file for pluxml
	alias.url += ("/pluxml" => "/usr/share/pluxml")
	EOF
    # Install file with ucf
    ucf --debconf-ok "$lighttpd_conf" /etc/pluxml/lighttpd.conf
    ucfr pluxml /etc/pluxml/lighttpd.conf
    # Remove temporary file
    rm -f "$lighttpd_conf"
}


# Enable lighttpd configuration
enable_lighttpd_conf()
{
    if [ -d /etc/lighttpd/conf-available -a ! -e /etc/lighttpd/conf-available/50-pluxml.conf ]
    then
        ln -s /etc/pluxml/lighttpd.conf /etc/lighttpd/conf-available/50-pluxml.conf
        if command -v lighty-enable-mod >/dev/null 2>/dev/null
        then
            lighty-enable-mod pluxml
        fi
    fi
}


# Reload lighttpd
reload_lighttpd()
{
    # That may fail if lighttpd is not running: this is not a real problem, so
    # ignore it
    invoke-rc.d lighttpd reload || true
}


# Generate blog configuration, managed by ucf
write_pluxml_conf()
{
    # Install special permissions overrides if requested
    db_get pluxml/system/writeconf
    writeconf="$RET"
    if [ "$writeconf" = "true" ]
    then
        if ! dpkg-statoverride --list /etc/pluxml >/dev/null 2>&1
        then
             dpkg-statoverride --update --add root www-data 0775 /etc/pluxml
        fi
        if ! dpkg-statoverride --list /etc/pluxml/plugins >/dev/null 2>&1
        then
             dpkg-statoverride --update --add root www-data 0775 /etc/pluxml/plugins
        fi
    fi
    # Creating main configuration file
    pluxml_parameters="$(tempfile)"
    db_get pluxml/blog/title
    title="$RET"
    db_get pluxml/blog/description
    description="$RET"
    db_get pluxml/blog/lang
    lang="$RET"
    if [ -e /etc/pluxml/adminkey ]
    then
        clef="$(grep -v '^#' /etc/pluxml/adminkey)"
    else
        clef="$(cat /dev/urandom| tr -dc A-Za-z | head -c15)"
    fi
    cat >> "$pluxml_parameters" <<- EOF
	<?xml version="1.0" encoding="UTF-8"?>
	<document>
	        <parametre name="title"><![CDATA[$title]]></parametre>
	        <parametre name="description"><![CDATA[$description]]></parametre>
	        <parametre name="meta_description"><![CDATA[$description]]></parametre>
	        <parametre name="meta_keywords"><![CDATA[]]></parametre>
	        <parametre name="timezone"><![CDATA[localtime]]></parametre>
	        <parametre name="allow_com">1</parametre>
	        <parametre name="mod_com">0</parametre>
	        <parametre name="mod_art">0</parametre>
	        <parametre name="capcha">1</parametre>
	        <parametre name="style"><![CDATA[defaut]]></parametre>
	        <parametre name="clef"><![CDATA[$clef]]></parametre>
	        <parametre name="bypage">5</parametre>
	        <parametre name="bypage_archives">5</parametre>
	        <parametre name="bypage_admin">10</parametre>
	        <parametre name="bypage_admin_coms">10</parametre>
	        <parametre name="bypage_feed">8</parametre>
	        <parametre name="tri"><![CDATA[desc]]></parametre>
	        <parametre name="tri_coms"><![CDATA[asc]]></parametre>
	        <parametre name="images_l">800</parametre>
	        <parametre name="images_h">600</parametre>
	        <parametre name="miniatures_l">200</parametre>
	        <parametre name="miniatures_h">100</parametre>
	        <parametre name="thumbs">1</parametre>
	        <parametre name="medias"><![CDATA[data/medias/]]></parametre>
	        <parametre name="documents"><![CDATA[data/documents/]]></parametre>
	        <parametre name="racine_articles"><![CDATA[../../../var/lib/pluxml/data/articles/]]></parametre>
	        <parametre name="racine_commentaires"><![CDATA[../../../var/lib/pluxml/data/commentaires/]]></parametre>
	        <parametre name="racine_statiques"><![CDATA[../../../var/lib/pluxml/data/statiques/]]></parametre>
	        <parametre name="racine_themes"><![CDATA[themes/]]></parametre>
	        <parametre name="racine_plugins"><![CDATA[plugins/]]></parametre>
	        <parametre name="homestatic"><![CDATA[]]></parametre>
	        <parametre name="hometemplate"><![CDATA[home.php]]></parametre>
	        <parametre name="urlrewriting">0</parametre>
	        <parametre name="gzip">0</parametre>
	        <parametre name="feed_chapo">0</parametre>
	        <parametre name="feed_footer"><![CDATA[]]></parametre>
	        <parametre name="version"><![CDATA[5.5]]></parametre>
	        <parametre name="default_lang"><![CDATA[$lang]]></parametre>
	        <parametre name="userfolders">0</parametre>
	        <parametre name="display_empty_cat">0</parametre>
	        <parametre name="custom_admincss_file"><![CDATA[]]></parametre>
	</document>
	EOF
    # Set correct permissions
    chown root:www-data "$pluxml_parameters"
    if [ "$writeconf" = "true" ]
    then
        chmod 664 "$pluxml_parameters"
    else
        chmod 644 "$pluxml_parameters"
    fi
    # Install file with ucf
    ucf --debconf-ok "$pluxml_parameters" /etc/pluxml/parametres.xml
    ucfr pluxml /etc/pluxml/parametres.xml
    # Remove temporary file
    rm -f "$pluxml_parameters"
    keyfile="$(tempfile)"
    cat >> "$keyfile" <<- EOF
	# Secret string used to restrict access to private RSS feeds such as online and
	# offline comments. This key is stored in parametres.xml, parameter name
	# "clef". This file exists to save it to keep the pluxml Debian package
	# configuration during upgrades.
	$clef
	EOF
    ucf --debconf-ok "$keyfile" /etc/pluxml/adminkey
    ucfr pluxml /etc/pluxml/adminkey
    # Remove temporary file
    rm -f "$keyfile"
    # Create user list file
    # Do not touch user lists of existing installations unless the user really
    # wants to reconfigure (in which case, the password will not be empty)
    db_get pluxml/blog/password
    password="$RET"
    if [ ! -e /etc/pluxml/users.xml -o -n "$password" ]
    then
        pluxml_users="$(tempfile)"
        db_get pluxml/blog/name
        name="$RET"
        db_get pluxml/blog/login
        login="$RET"
        db_get pluxml/blog/password
        password="$RET"
        salt="$(cat /dev/urandom| tr -dc A-Za-z | head -c10)"
        password="$(printf '%s' "$password" | md5sum | cut -d' ' -f1)"
        password="$(printf '%s%s' "$salt" "$password" | sha1sum | cut -d' ' -f1)"
        # Remove password from debconf database
        db_set pluxml/blog/password ""
        db_set pluxml/blog/confirm ""
        cat >> "$pluxml_users" <<- EOF
	<?xml version="1.0" encoding="utf-8"?>
	<document>
	        <user number="001" active="1" profil="0" delete="0">
	                <login><![CDATA[$login]]></login>
	                <name><![CDATA[$name]]></name>
	                <infos><![CDATA[]]></infos>
	                <password><![CDATA[$password]]></password>
	                <salt><![CDATA[$salt]]></salt>
	                <email></email>
	                <lang><![CDATA[$lang]]></lang>
	        </user>
	</document>
	EOF
        # Set correct permissions
        chown root:www-data "$pluxml_users"
        if [ "$writeconf" = "true" ]
        then
            chmod 660 "$pluxml_users"
        else
            chmod 640 "$pluxml_users"
        fi
        # Install file with ucf
        ucf --debconf-ok "$pluxml_users" /etc/pluxml/users.xml
        ucfr pluxml /etc/pluxml/users.xml
        # Remove temporary file
        rm -f "$pluxml_users"
    fi
}


# Generate default blog content, which should be neither part of the package
# files nor managed configuration
write_pluxml_content()
{
    if [ ! -e /var/lib/pluxml/data/configuration/plugins.xml ]
    then
        cat >> /var/lib/pluxml/data/configuration/plugins.xml <<- EOF
	<?xml version="1.0" encoding="utf-8"?>
	<document>
	</document>
	EOF
        chown www-data:root /var/lib/pluxml/data/configuration/plugins.xml
    fi
    if [ ! -e /var/lib/pluxml/data/configuration/categories.xml ]
    then
        cat >> /var/lib/pluxml/data/configuration/categories.xml <<- EOF
	<?xml version="1.0" encoding="utf-8"?>
	<document>
	        <categorie number="001" active="1" homepage="1" tri="desc" bypage="5" menu="oui" url="caregory-1" template="categorie.php">
	                <name><![CDATA[Category 1]]></name>
	                <description><![CDATA[]]></description>
	                <meta_description><![CDATA[]]></meta_description>
	                <meta_keywords><![CDATA[]]></meta_keywords>
	                <title_htmltag><![CDATA[]]></title_htmltag>
	        </categorie>
	</document>
	EOF
        chown www-data:root /var/lib/pluxml/data/configuration/categories.xml
    fi
    if [ ! -e /var/lib/pluxml/data/statiques/001.static-1.php ]
    then
        cat >> /var/lib/pluxml/data/statiques/001.static-1.php <<- EOF
	<p>My first static page!</p>
	EOF
        chown www-data:root /var/lib/pluxml/data/statiques/001.static-1.php
    fi
    if [ ! -e /var/lib/pluxml/data/configuration/statiques.xml ]
    then
        cat >> /var/lib/pluxml/data/configuration/statiques.xml <<- EOF
	<?xml version="1.0" encoding="utf-8"?>
	<document>
	        <statique number="001" active="1" menu="oui" url="static-1" template="static.php">
	                <group><![CDATA[]]></group>
	                <name><![CDATA[Static 1]]></name>
	                <meta_description><![CDATA[]]></meta_description>
	                <meta_keywords><![CDATA[]]></meta_keywords>
	                <title_htmltag><![CDATA[]]></title_htmltag>
	        </statique>
	</document>
	EOF
        chown www-data:root /var/lib/pluxml/data/configuration/statiques.xml
    fi
    date="$(date '+%Y%m%d%H%M')"
    if [ -z "$(find /var/lib/pluxml/data/articles -maxdepth 1 -name '0001.001.001.*.first-article.xml' -print -quit)" ]
    then
        cat >> /var/lib/pluxml/data/articles/"0001.001.001.$date.first-article.xml" <<- EOF
	<?xml version="1.0" encoding="utf-8"?>
	<document>
	        <title><![CDATA[First article]]></title>
	        <allow_com>1</allow_com>
	        <template><![CDATA[article.php]]></template>
	        <chapo>
	                <![CDATA[]]>
	        </chapo>
	        <content>
	                <![CDATA[<p>This article was created during PluXml installation. Edit it from the administration.</p>]]>
	        </content>
	        <tags>
	                <![CDATA[PluXml]]>
	        </tags>
	        <meta_description>
	                <![CDATA[]]>
	        </meta_description>
	        <meta_keywords>
	                <![CDATA[]]>
	        </meta_keywords>
	        <title_htmltag>
	                <![CDATA[]]>
	        </title_htmltag>
	</document>
	EOF
        chown www-data:root /var/lib/pluxml/data/articles/"0001.001.001.$date.first-article.xml"
    fi
    if [ ! -e /var/lib/pluxml/data/configuration/tags.xml ]
    then
        cat >> /var/lib/pluxml/data/configuration/tags.xml <<- EOF
	<?xml version="1.0" encoding="utf-8"?>
	<document>
	        <article number="0001" date="$date" active="1"><![CDATA[PluXml]]></article>
	</document>
	EOF
        chown www-data:root /var/lib/pluxml/data/configuration/tags.xml
    fi
    timestamp="$(date '+%s')"
    if [ -z "$(find /var/lib/pluxml/data/commentaires -maxdepth 1 -name '0001.*-1.xml' -print -quit)" ]
    then
        cat >> /var/lib/pluxml/data/commentaires/"0001.$timestamp-1.xml" <<- EOF
	<?xml version="1.0" encoding="UTF-8"?>
	<comment>
	        <author><![CDATA[pluxml]]></author>
	        <type>normal</type>
	        <ip>127.0.0.1</ip>
	        <mail><![CDATA[contact@pluxml.org]]></mail>
	        <site><![CDATA[http://www.pluxml.org]]></site>
	        <content><![CDATA[This is a first comment !]]></content>
	</comment>
	EOF
        chown www-data:root /var/lib/pluxml/data/commentaires/"0001.$timestamp-1.xml"
    fi
}

upgrade_5_4()
{
    # The images directory has been replaced by a medias directory
    if [ -d /var/lib/pluxml/data/images ] && \
       [ ! -h /var/lib/pluxml/data/images ]
    then
        # Move images to the new directory
        find /var/lib/pluxml/data/images \
             -mindepth 1 -maxdepth 1 \
             -execdir mv '{}' /var/lib/pluxml/data/medias ';'
        rmdir /var/lib/pluxml/data/images
        # Change references to these files in articles and static pages
        find /var/lib/pluxml/data/articles /var/lib/pluxml/data/statiques \
             -type f  -a  '(' -name '*.xml' -o -name '*.php' ')' \
             -execdir sed -i -e 's_src="data/images/_src="data/medias/_g' \
                          '{}' +
    fi
    # Update version number in configuration file
    sed -ri '/<parametre name="version">/s/5\.[[:digit:]\.]*/5.4/' \
        /etc/pluxml/parametres.xml
}

upgrade_5_5()
{
    # The comments naming has changed, from:
    #     ${artid}.${timestamp}-${index}.xml    (published comments)
    #     _${artid}.${timestamp}-${index}.xml   (offline comments)
    # where ${index} was only increased for possible collisions, to:
    #     ${artid}.${timestamp}-${index}.xml    (published comments)
    #     _${artid}.${timestamp}-${index}.xml   (offline comments)
    # where ${index} is now increased for each comment in the same article.
    printf > /dev/stderr 'Reindexing comments on /var/lib/pluxml/data/commentaires... '
    # Temporary directory to store reindexed comments without colliding to
    # non-reindexed ones.
    mkdir /var/lib/pluxml/data/commentaires.new
    find /var/lib/pluxml/data/commentaires \
         -mindepth 1 -maxdepth 1 -regextype posix-extended \
         -regex '.*/[[:punct:]]?[[:digit:]]{4}\.[[:digit:]]{10}-[[:digit:]]+\.xml' \
    | sort \
    | (
        current_article='0000'
        current_index=0
        while read comment
        do
            comment_info="$(
                printf '%s\n' "$comment" \
                | sed -r 's/^.*\/([[:punct:]]?)([[:digit:]]{4})\.([[:digit:]]{10})-([[:digit:]])+\.xml$/\1:\2:\3:\4/')"
            comment_status="${comment_info%%:*}"
            comment_article="${comment_info#$comment_status:}"
            comment_article="${comment_article%%:*}"
            comment_timestamp="${comment_info#$comment_status:$comment_article:}"
            comment_timestamp="${comment_timestamp%%:*}"
            comment_index="${comment_info#$comment_status:$comment_article:$comment_timestamp}"
            comment_index="${comment_index%.xml}"
            if [ "$comment_article" = "$current_article" ]
            then
                comment_newindex=$(($current_index + 1))
            else
                current_article="$comment_article"
                comment_newindex=1
            fi
            current_index=$comment_newindex
            # Move the comment to the temporary directory with its new reindexed name
            comment_new="$(printf '%s/%s%s.%s-%s.xml' \
                                  '/var/lib/pluxml/data/commentaires.new' \
                                  "$comment_status" "$comment_article" \
                                  "$comment_timestamp" "$comment_newindex")"
            mv -- "$comment" "$comment_new"
        done
    )
    # Move all reindexed comments back to the comments directory
    find /var/lib/pluxml/data/commentaires.new \
        -mindepth 1 -maxdepth 1 \
        -execdir mv -- '{}' /var/lib/pluxml/data/commentaires ';'
    # And remove the now empty temporary reindexed comments directory
    rmdir /var/lib/pluxml/data/commentaires.new
    printf > /dev/stderr '[done]\n'
    # Update version number in configuration file
    sed -ri '/<parametre name="version">/s/5\.[[:digit:]\.]*/5.5/' \
        /etc/pluxml/parametres.xml
}

# Main script
case "$1" in
    configure)
        . /usr/share/debconf/confmodule
        write_pluxml_conf
        write_pluxml_content
        case "$2"
        in
            5.2*|5.3*)
                upgrade_5_4
                upgrade_5_5
            ;;
            5.4*)
                upgrade_5_5
            ;;
        esac
        # Write a configuration file for all the supported webservers
        write_apache2_conf
        write_lighttpd_conf
        # Only apply the configuration to the chosen webservers
        db_get pluxml/system/webservers
        webservers="$RET"
        db_get pluxml/system/reload-webserver
        reload_webserver="$RET"
        for webserver in $webservers
        do
            webserver=${webserver%,}
            enable_${webserver}_conf "$@"
            if [ "$reload_webserver" = "true" ]
            then
                reload_$webserver "$@"
            fi
        done
        db_stop
    ;;

    abort-upgrade|abort-remove|abort-deconfigure)
    ;;

    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0
