/* pathname_watcher.cc
 * This file belongs to Worker, a file manager for UN*X/X11.
 * Copyright (C) 2012 Ralf Hoffmann.
 * You can contact me at: ralf@boomerangsworld.de
 *   or http://www.boomerangsworld.de/worker
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "pathname_watcher.hh"

#ifdef HAVE_INOTIFY
#  include <sys/inotify.h>
#endif

#include <iostream>
#include <set>

PathnameWatcher::PathnameWatcher() : m_inotify_fd( -1 )
{
#ifdef HAVE_INOTIFY
    m_inotify_fd = inotify_init();
#endif
}

PathnameWatcher::~PathnameWatcher()
{
    unwatchAll();

    if ( m_inotify_fd != -1 ) {
        close( m_inotify_fd );
    }
}

int PathnameWatcher::getWatcherFD()
{
    return m_inotify_fd;
}

int PathnameWatcher::watchPath( const std::string &pathname )
{
#ifdef HAVE_INOTIFY
    int res;

    if ( m_inotify_fd == -1 ) return -1;

    if ( m_watched_paths.count( pathname ) > 0 ) {
        m_watched_paths[ pathname ].second++;
        return m_watched_paths[ pathname ].first;
    }

    res = inotify_add_watch( m_inotify_fd,
                             pathname.c_str(),
                             /*IN_ALL_EVENTS*/
                             IN_MODIFY | IN_ATTRIB | IN_MOVE | IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MOVE_SELF );

    if ( res != -1 ) {
        m_watched_paths[ pathname ] = std::make_pair( res, 1 );
    }

    return res;
#else
    return -1;
#endif
}

int PathnameWatcher::unwatchPath( const std::string &pathname, bool force )
{
#ifdef HAVE_INOTIFY
    if ( m_inotify_fd == -1 ) return -1;

    if ( m_watched_paths.count( pathname ) > 0 ) {
        if ( --( m_watched_paths[ pathname ].second ) == 0 || force == true ) {
            int res = inotify_rm_watch( m_inotify_fd, m_watched_paths[ pathname ].first );

            m_watched_paths.erase( pathname );

            return res;
        }
    }
#endif

    return 0;
}

int PathnameWatcher::unwatchAll()
{
#ifdef HAVE_INOTIFY
    if ( m_inotify_fd == -1 ) return -1;

    for ( std::map< std::string, std::pair< int, int > >::const_iterator it1 = m_watched_paths.begin();
          it1 != m_watched_paths.end();
          it1++ ) {
        inotify_rm_watch( m_inotify_fd, it1->second.first );
    }

    m_watched_paths.clear();
#endif

    return 0;
}

std::list< std::string > PathnameWatcher::getChangedPaths()
{
    std::list< std::string > res;
    std::set< std::string > already_known;

#ifdef HAVE_INOTIFY
    if ( m_inotify_fd != -1 ) {
        for (;;) {
            fd_set s;
            struct timeval tv;

            FD_ZERO( &s );

            FD_SET( m_inotify_fd, &s );

            tv.tv_sec = 0;
            tv.tv_usec = 0;

            if ( select( m_inotify_fd + 1, &s, NULL, NULL, &tv ) == 1 ) {

                if ( ! FD_ISSET( m_inotify_fd, &s ) ) break;

                // something available

                struct inotify_event *event;
                char buf[1024 * sizeof( *event )];
                ssize_t read_bytes;
                ssize_t i = 0;

                read_bytes = read( m_inotify_fd, &buf, sizeof( buf ) / sizeof( buf[0] ) );

                while ( i < read_bytes && read_bytes - i >= ssize_t( sizeof( *event ) ) ) {

                    event = (struct inotify_event *)( &buf[i] );

                    if ( ( event->mask & ( IN_UNMOUNT | IN_IGNORED ) ) == 0 ) {
                        // ignore unmount events

                        for ( std::map< std::string, std::pair< int, int > >::const_iterator it1 = m_watched_paths.begin();
                              it1 != m_watched_paths.end();
                              it1++ ) {
                            if ( event->wd == it1->second.first && already_known.count( it1->first ) == 0 ) {
                                res.push_back( it1->first );
                                already_known.insert( it1->first );

                                // got an event for the path and stored in result
                                // so unwatch this path to avoid tons of events in case
                                // of fast updates
                                // the user must rewatch it
                                unwatchPath( it1->first, true );
                                break;
                            }
                        }
                    }

                    i += sizeof( *event ) + event->len;
                }
            } else {
                break;
            }
        }
    }
#endif

    return res;
}
