#!/bin/bash -e
if [ -z $CONTAINER ]; then
    echo "PAS DE CONTAINER"
    exit 1
fi
ROOT="/var/lib/risotto/images/$CONTAINER"
echo "$ROOT"
DESTDIR="$ROOT/usr/lib/tmpfiles.d"
CONF_DST="/usr/share/factory"
EXCLUDES="^($ROOT/etc/passwd|$ROOT/etc/group|$ROOT/etc/.updated|$ROOT/etc/.pwd.lock|$ROOT/etc/systemd/network/dhcp.network|$ROOT/etc/sudoers.d/qemubuild)$"
ONLY_COPY="^($ROOT/etc/localtime)$"
FORCE_LINKS="^($ROOT/etc/udev/hwdb.bin)$"

function execute() {
    chroot $ROOT $@
}

function file_dir_in_tmpfiles() {
    letter=$1
    directory=$2
    local_directory=$(echo $directory|sed "s@^$ROOT@@g")
    mode=$(execute "/usr/bin/stat" "--format" "%a" "$local_directory" | grep -o "[0-9.]\+")
    user=$(execute "/usr/bin/stat" "--format" "%U" "$local_directory" | grep -o "[0-9a-zA-Z.-]\+")
    group=$(execute "/usr/bin/stat" "--format" "%G" "$local_directory" | grep -o "[0-9a-zA-Z.-]\+")
    echo "$letter $local_directory $mode $user $group - -"
}

function calc_symlink_in_tmpfiles() {
    dest_name=$1
    local_dest_name=$2
    src_file=$(readlink "$dest_name")
    symlink_in_tmpfiles "$local_dest_name" "$src_file"
}

function symlink_in_tmpfiles() {
    dest_name=$1
    src_file=$2
    echo "L+ $dest_name - - - - $src_file"
}

function main() {
    dir_config_orig=$1
    name="${dir_config_orig//\//-}"
    dir_config_orig=$ROOT$dir_config_orig

    mkdir -p "$DESTDIR"
    mkdir -p "$ROOTCONF_DST$dir_config_orig"
    systemd_conf="$DESTDIR/risotto$name.conf"
    rm -f $systemd_conf
    shopt -s globstar
    for src_file in $dir_config_orig/**; do
        local_src=$(echo $src_file|sed "s@$ROOT@@g")
        dest_file="$ROOT$CONF_DST$local_src"
        if [[ "$src_file" =~ $EXCLUDES ]]; then
             echo "$src_file: exclude" >&2
        elif [[ -L "$src_file" ]]; then
            calc_symlink_in_tmpfiles "$src_file" "$local_src" >> $systemd_conf
        elif [[ "$src_file" =~ $FORCE_LINKS ]]; then
            symlink_in_tmpfiles "$src_file" "$dest_file" >> $systemd_conf
        elif [[ -d "$src_file" ]]; then
            file_dir_in_tmpfiles 'd' "$src_file" >> $systemd_conf
            [[ ! -d "$dest_file" ]] && mkdir -p "$dest_file"
            #echo "$src_file: directory ok"
        else
            if [[ ! "$src_file" =~ $ONLY_COPY ]]; then
                file_dir_in_tmpfiles "C" "$src_file" >> $systemd_conf
            fi
            [[ -e "$dest_file" ]] && rm -f "$dest_file"
            # not a symlink... an hardlink
            ln "$src_file" "$dest_file"
            #echo "$src_file: file ok"
        fi
    done
}
main "$1"
echo "fin"
exit 0
