#!/bin/bash
#
# ** header v3.0
# This file is a part of the CaosDB Project.
#
# Copyright (C) 2018 Research Group Biomedical Physics,
# Max-Planck-Institute for Dynamics and Self-Organization Göttingen
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
# ** end header
#

function is_dir_in(){
    [ -d "$2/$1" ]
}

function has_symlink_in_dir(){
    [ -L "$2/$1" ]
}

function symlink_ok(){
    [ -e "$1" ]
}

function is_empty(){
    [[ -z "$(find -L $1 -type f)" ]] 
}

IFS=$(echo -en "\n\b")
function check_recursively() {
    local symlink_dir=$1
    local orig_dir=$2

    # check if all symlinks are unbroken
    for symlink in $(find $symlink_dir -maxdepth 1 -mindepth 1 -type l)
    do 
        if ! symlink_ok $symlink
        then
            echo -e "[ERROR broken link]\n\t$symlink is broken link."
        fi
    done

    # check if a symlink exists for all files
    for file in $(find $orig_dir -maxdepth 1 -mindepth 1 -type f)
    do
        local filename=$(basename "$file")
        if ! has_symlink_in_dir $filename $symlink_dir
        then 
            echo -e "[ERROR unlinked file]\n\t$filename has no symlink in $symlink_dir."
        fi
    done

    # check if a directory exists for all directories
    for subdir in $(find $orig_dir -maxdepth 1 -mindepth 1 -type d)
    do
        if ! is_empty $subdir
        then
            local dirname=$(basename "$subdir")
            if ! is_dir_in $dirname $symlink_dir and ! is_empty $subdir 
            then
                echo -e "[ERROR missing dir]\n\t$dirname is not in $symlink_dir."
            else
                check_recursively $symlink_dir/$dirname $subdir
            fi
        else
            echo "$subdir is empty"
        fi
    done
}

check_recursively ${1%/} ${2%/}
