#!/usr/bin/env bash
# w4os-site-tree: the site as a normal Grav site, the web user's, which Grav's own tools (GPM, the admin) update; run by the
# package (postinst), its functions sourced by the tests.
#
#   w4os-site-tree configure
#       a new site: the site the package ships (its seed) copied where it is served, the content of an install of before moved
#       into it (the content of the site, the plugins and themes added to it, the web server configuration it wrote); a site in
#       the folder of before (/var/lib/opensim/www) moved to its folder, a link left where it was; an existing
#       site: what the package ships of it replaced where the site still has it as the package put it (Grav, each plugin, each
#       theme, each default page), the rest left as it is and said; a new default page added, unless the site has one at its route. Where the PHP of the site is older than 8.3 (Debian 12), Grav is Grav 1.7 and Quark 2
#       the last one for it (the package's site-grav17), until a configure finds a PHP that runs Grav 2
#
# The places, for the tests: W4OS_SITE_SEED (/usr/share/w4os-site/site), W4OS_SITE_ROOT (/var/lib/w4os/www), W4OS_SITE_PREVIOUS
# (/var/lib/opensim/www, the folder of the site before), W4OS_SITE_OLD (/var/lib/w4os-site, the content of the site of before),
# W4OS_SITE_OLD_TREE (/usr/share/w4os-site/grav, its Grav of before), W4OS_SITE_APACHE (/etc/apache2/sites-available/w4os-site.conf),
# W4OS_SITE_OWNER and W4OS_SITE_GROUP (WebUser and WebGroup of the engine's w4os.conf, www-data without them), W4OS_SITE_LEGACY
# (/usr/share/w4os-site/site-grav17, the units for PHP older than 8.3), W4OS_SITE_PHP (php, the PHP whose version chooses),
# W4OS_SITE_PAGES_HISTORY (/usr/share/w4os-site/pages-history, the texts each version of the package gave the default pages).
set -eo pipefail

SEED=${W4OS_SITE_SEED:-/usr/share/w4os-site/site}
ROOT=${W4OS_SITE_ROOT:-/var/lib/w4os/www}
PREVIOUS=${W4OS_SITE_PREVIOUS:-/var/lib/opensim/www}
OLD=${W4OS_SITE_OLD:-/var/lib/w4os-site}
OLD_TREE=${W4OS_SITE_OLD_TREE:-/usr/share/w4os-site/grav}
APACHE=${W4OS_SITE_APACHE:-/etc/apache2/sites-available/w4os-site.conf}
OWNER=${W4OS_SITE_OWNER:-}
GROUP=${W4OS_SITE_GROUP:-$OWNER}
LEGACY=${W4OS_SITE_LEGACY:-/usr/share/w4os-site/site-grav17}
PAGES_HISTORY=${W4OS_SITE_PAGES_HISTORY:-/usr/share/w4os-site/pages-history}
# Set by configure where the units of LEGACY replace the seed's: PHP older than 8.3, which Grav 2 needs
ON_LEGACY=
# What the package put, and how (the checksum of each file), to know what the site changed since
MANIFEST=user/data/w4os-site/manifest

say() { echo "w4os-site: $*"; }

# web_account: the account and group of the web server ("user group"), as the engine of the machine resolves them (WebUser and
# WebGroup of w4os.conf, its profile over [Defaults]), read with the engine the site's w4os plugin carries; www-data without them
web_account() {
    local vendor
    for vendor in "$ROOT/user/plugins/w4os/vendor" "${SEED:-$ROOT}/user/plugins/w4os/vendor"; do
        [ -f "$vendor/autoload.php" ] || continue
        ${W4OS_SITE_PHP:-php} -r 'require $argv[1]; $layout = W4OS\Engine\Config\Layout::load(); echo $layout->webUser(), " ", $layout->webGroup(), PHP_EOL;' \
            "$vendor/autoload.php" 2>/dev/null && return
    done
    echo "www-data www-data"
}

# file_sum FILE: its checksum
file_sum() {
    if command -v md5sum >/dev/null; then md5sum <"$1" | cut -d' ' -f1; else md5 -q "$1"; fi
}

# units TREE: what the package ships and replaces as a whole: Grav (core), each plugin, each theme, each default page
units() {
    local dir
    echo core
    for dir in "$1"/user/plugins/*/ "$1"/user/themes/*/ "$1"/user/pages/*/; do
        [ -d "$dir" ] || continue
        dir=${dir%/}
        echo "${dir#"$1"/user/}"
    done
}

# unit_files TREE UNIT: the files of a unit, from the root of TREE; Grav without the site's own (user/) and what it writes
unit_files() {
    if [ "$2" = core ]; then
        (cd "$1" && find . -type f -not -path './user/*' -not -path './cache/*' -not -path './logs/*' -not -path './tmp/*' \
            -not -path './backup/*' -not -path './assets/*' -not -path './images/*' | sed 's#^\./##' | LC_ALL=C sort)
    elif [ -d "$1/user/$2" ]; then
        (cd "$1" && find "user/$2" -type f | LC_ALL=C sort)
    fi
}

# as_put UNIT OLDMANIFEST: whether the site still has the files of UNIT as the package put them (none changed or removed);
# the files the site added (a logo copied into a theme) do not count
as_put() {
    local unit sum file found=
    while IFS=$'\t' read -r unit sum file; do
        [ "$unit" = "$1" ] || continue
        found=1
        [ -f "$ROOT/$file" ] && [ "$(file_sum "$ROOT/$file")" = "$sum" ] || return 1
    done <"$2"
    [ -n "$found" ]
}

# source_of UNIT: the tree the package takes UNIT from: LEGACY for its units where the PHP of the site is older than 8.3, the seed else
source_of() {
    if [ -n "$ON_LEGACY" ] && { [ "$1" = core ] || [ -d "$LEGACY/user/$1" ]; }; then echo "$LEGACY"; else echo "$SEED"; fi
}

# put UNIT [OLDMANIFEST]: the files of UNIT copied from its source into the site, the ones of before that it no longer has removed
put() {
    local unit=$1 old=${2:-} from sum file
    from=$(source_of "$unit")
    if [ -n "$old" ]; then
        local u
        while IFS=$'\t' read -r u sum file; do
            [ "$u" = "$unit" ] && [ ! -f "$from/$file" ] && rm -f "${ROOT:?}/$file"
        done <"$old"
    fi
    (cd "$from" && unit_files . "$unit" | tar -cf - -T -) | (cd "$ROOT" && tar -xf -)
}

# install: the seed where the site is served, a new site; the units of LEGACY instead of its own where they are the ones to put
install_site() {
    local unit
    [ -d "$(dirname "$ROOT")" ] || install -d -m 755 "$(dirname "$ROOT")"
    cp -Rp "$SEED" "$ROOT"
    [ -n "$ON_LEGACY" ] || return 0
    while read -r unit; do
        (cd "$ROOT" && unit_files "$SEED" "$unit" | while read -r file; do rm -f "$file"; done)
        put "$unit"
    done < <(units "$LEGACY")
}

# migrate: the content of the site of before (its config, pages, accounts, data, sessions; the plugins and themes added to its
# Grav) into the new site; the folders of before kept aside, renamed .migrated
migrate() {
    local dir
    for dir in config pages accounts data; do
        [ -d "$OLD/$dir" ] || continue
        rm -rf "${ROOT:?}/user/$dir"
        cp -Rp "$OLD/$dir" "$ROOT/user/$dir"
    done
    if [ -d "$OLD/sessions" ]; then
        mkdir -p "$ROOT/user/data/sessions"
        cp -Rp "$OLD/sessions/." "$ROOT/user/data/sessions/"
    fi
    for dir in "$OLD_TREE"/user/plugins/*/ "$OLD_TREE"/user/themes/*/; do
        [ -d "$dir" ] || continue
        dir=${dir%/}
        dir=${dir#"$OLD_TREE"/}
        [ -e "$ROOT/$dir" ] || { cp -Rp "$OLD_TREE/$dir" "$ROOT/$dir" && say "$dir, added to the site of before, kept"; }
    done
    mv "$OLD" "$OLD.migrated"
    [ ! -d "$OLD_TREE" ] || mv "$OLD_TREE" "$OLD.migrated/grav"
    # The Apache configuration w4os-site web wrote (its first line says so): the new root; any other is the admin's to change
    if [ -f "$APACHE" ] && grep -q '/usr/share/w4os-site/grav' "$APACHE"; then
        if head -1 "$APACHE" | grep -q '^# The w4os site'; then
            sed -i.bak -e "s#/usr/share/w4os-site/grav#$ROOT#g" -e '/<Directory \/var\/cache\/w4os-site>/,/<\/Directory>/d' "$APACHE"
            rm -f "$APACHE.bak"
            say "$APACHE: the site served from $ROOT"
        else
            say "$APACHE serves /usr/share/w4os-site/grav: change it to $ROOT"
        fi
    fi
    say "the site is now in $ROOT (its content of before kept in $OLD.migrated)"
}

# move: the site of the folder of before moved to its folder, a link left there for what still serves it from there; the Apache
# configuration w4os-site web wrote (its first line says so) serves it from its folder, any other is the admin's to change
move() {
    [ -d "$(dirname "$ROOT")" ] || install -d -m 755 "$(dirname "$ROOT")"
    mv "$PREVIOUS" "$ROOT"
    ln -s "$ROOT" "$PREVIOUS"
    if [ -f "$APACHE" ] && grep -q "$PREVIOUS" "$APACHE"; then
        if head -1 "$APACHE" | grep -q '^# The w4os site'; then
            sed -i.bak "s#$PREVIOUS#$ROOT#g" "$APACHE"
            rm -f "$APACHE.bak"
            say "$APACHE: the site served from $ROOT"
        else
            say "$APACHE serves $PREVIOUS: change it to $ROOT"
        fi
    fi
    say "the site is now in $ROOT ($PREVIOUS links to it)"
}

# given UNIT: whether a default page the manifest does not know yet (a site of before the pages were units) is as a version of the
# package gave it: each of its texts the seed's or one of the history of the package (the site's own files, its pictures, aside)
given() {
    local file sum found=
    [[ $1 == pages/* ]] || return 1
    while read -r file; do
        found=1
        sum=$(file_sum "$ROOT/$file")
        [ -f "$SEED/$file" ] && [ "$(file_sum "$SEED/$file")" = "$sum" ] && continue
        [ -f "$PAGES_HISTORY" ] && grep -qx "$file	$sum" "$PAGES_HISTORY" && continue
        return 1
    done < <(cd "$ROOT" && find "user/$1" -type f -name '*.md' | LC_ALL=C sort)
    [ -n "$found" ]
}

# gone UNIT MANIFEST: whether a default page the package no longer has is as the package put it (its manifest, else, for a site of
# before the pages were units, the texts of its versions) with nothing of the site's own in it (a picture): what an upgrade removes
gone() {
    local listed extra
    [[ $1 == pages/* ]] && [ -d "$ROOT/user/$1" ] || return 1
    if grep -q "^$1	" "$2"; then
        as_put "$1" "$2" || return 1
        listed=$(grep "^$1	" "$2" | cut -f3 | LC_ALL=C sort)
    else
        given "$1" || return 1
        listed=$(cd "$ROOT" && find "user/$1" -type f -name '*.md' | LC_ALL=C sort)
    fi
    extra=$(cd "$ROOT" && find "user/$1" -type f | LC_ALL=C sort | comm -23 - <(echo "$listed"))
    [ -z "$extra" ]
}

# taken UNIT: the route of a default page (its folder without its number), when the site has another page there
taken() {
    local name=${1#pages/} dir slug
    slug=${name#[0-9]*.}
    for dir in "$ROOT"/user/pages/*/; do
        dir=$(basename "$dir")
        [ "$dir" != "$name" ] && { [ "$dir" = "$slug" ] || [ "${dir#[0-9]*.}" = "$slug" ]; } && echo "/$slug" && return 0
    done
    return 1
}

# upgrade: each unit the site has as the package put it replaced by the seed's, the others left and said; the new ones added; a
# default page the package no longer has removed where the site has it as the package put it, left (and said) where it changed it
upgrade() {
    local old="$ROOT/$MANIFEST" new kept unit
    new=$(mktemp)
    kept=$(mktemp)
    [ -f "$old" ] || : >"$old"
    while read -r unit; do
        if [ "$unit" != core ] && [ ! -e "$ROOT/user/$unit" ]; then
            # Removed from the site by its admin: left out; new in the package: added
            if grep -q "^$unit	" "$old"; then
                say "$unit removed from this site, left out"
                continue
            fi
            local route
            if [[ $unit == pages/* ]] && route=$(taken "$unit"); then
                say "$unit: the site has its own page at $route, left out"
                continue
            fi
            put "$unit"
            say "$unit added"
        elif as_put "$unit" "$old" || { ! grep -q "^$unit	" "$old" && given "$unit"; }; then
            put "$unit" "$old"
        else
            grep "^$unit	" "$old" >>"$kept" || true
            say "$unit changed on this site, left as it is"
            continue
        fi
        manifest_unit "$unit" >>"$new"
    done < <(units "$SEED")
    while read -r unit; do
        units "$SEED" | grep -qx "$unit" && continue
        [ -d "$ROOT/user/$unit" ] || continue
        if gone "$unit" "$old"; then
            rm -rf "${ROOT:?}/user/$unit"
            say "$unit no longer in the package, removed"
        else
            grep "^$unit	" "$old" >>"$kept" || true
            say "$unit no longer in the package, changed on this site: left as it is"
        fi
    done < <({ cut -f1 "$old"; [ ! -f "$PAGES_HISTORY" ] || sed -n 's#^user/\(pages/[^/	]*\)/.*#\1#p' "$PAGES_HISTORY"; } | grep '^pages/' | LC_ALL=C sort -u)
    cat "$kept" "$new" >"$old"
    rm -f "$new" "$kept"
}

# manifest_unit UNIT: the lines of the manifest for UNIT as the package puts it (from its source)
manifest_unit() {
    local file from
    from=$(source_of "$1")
    unit_files "$from" "$1" | while read -r file; do
        printf '%s\t%s\t%s\n' "$1" "$(file_sum "$from/$file")" "$file"
    done
}

configure() {
    local php
    php=$(${W4OS_SITE_PHP:-php} -r 'echo PHP_VERSION_ID;' 2>/dev/null || echo 0)
    if [ -d "$LEGACY" ] && [ "$php" -lt 80300 ]; then
        ON_LEGACY=1
        say "PHP $(${W4OS_SITE_PHP:-php} -r 'echo PHP_VERSION;' 2>/dev/null): Grav 1.7 (Grav 2 needs PHP 8.3), until PHP is 8.3 or newer"
    fi
    [ -d "$ROOT" ] || [ -L "$PREVIOUS" ] || [ ! -d "$PREVIOUS" ] || move
    if [ ! -d "$ROOT" ]; then
        install_site
        [ ! -d "$OLD" ] || [ -d "$OLD.migrated" ] || migrate
        mkdir -p "$(dirname "$ROOT/$MANIFEST")"
        # What the site has of the seed: the pages of a site of before stay its own, the default ones it lacks are new to it
        units "$SEED" | while read -r unit; do
            [ "$unit" = core ] || [ -e "$ROOT/user/$unit" ] || continue
            manifest_unit "$unit"
        done >"$ROOT/$MANIFEST"
    else
        upgrade
    fi
    # What Grav compiled for the code of before
    rm -rf "${ROOT:?}/cache/"* 2>/dev/null || true
    [ -n "$OWNER" ] || read -r OWNER GROUP < <(web_account) || true
    [ "$(id -u)" != 0 ] || chown -R "$OWNER:$GROUP" "$ROOT"
    # The sessions, for the web server alone
    mkdir -p "$ROOT/user/data/sessions"
    chmod 700 "$ROOT/user/data/sessions"
}

if [ "${BASH_SOURCE[0]}" = "$0" ]; then
    case ${1:-} in
    configure) configure ;;
    *) sed -n '4,9p' "$0" | sed 's/^# \{0,1\}//'; exit 1 ;;
    esac
fi
