/* filelock.cc
 * This file belongs to Worker, a file manager for UN*X/X11.
 * Copyright (C) 2010-2019 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 "filelock.hh"
#include "aguix/lowlevelfunc.h"

FileLock::FileLock( const std::string &filename ) : m_filename( filename ),
                                                    m_fd( -1 )
{
}


FileLock::~FileLock()
{
    unlock();
}

bool FileLock::trylock()
{
    m_fd = open( m_filename.c_str(),
                 O_CREAT | O_WRONLY,
                 S_IRUSR | S_IWUSR );
    if ( m_fd == -1 ) return false;

    struct flock fl;

    memset( &fl, 0, sizeof( fl ) );
    fl.l_type = F_WRLCK;
    fl.l_whence = SEEK_SET;
    fl.l_start = 0;
    fl.l_len = 0;

    int res = fcntl( m_fd,
                     F_SETLK,
                     &fl );

    if ( res == 0 ) return true;
    
    return false;
}

bool FileLock::lock()
{
    m_fd = open( m_filename.c_str(),
                 O_CREAT | O_WRONLY,
                 S_IRUSR | S_IWUSR );
    if ( m_fd == -1 ) return false;

    struct flock fl;

    memset( &fl, 0, sizeof( fl ) );
    fl.l_type = F_WRLCK;
    fl.l_whence = SEEK_SET;
    fl.l_start = 0;
    fl.l_len = 0;

    while ( true ) {
        int res = fcntl( m_fd,
                         F_SETLKW,
                         &fl );

        if ( res == 0 ) return true;
    }
    
    return false;
}

void FileLock::unlock()
{
    if ( m_fd == -1 ) return;

    struct flock fl;

    memset( &fl, 0, sizeof( fl ) );
    fl.l_type = F_UNLCK;
    fl.l_whence = SEEK_SET;
    fl.l_start = 0;
    fl.l_len = 0;

    fcntl( m_fd,
           F_SETLK,
           &fl );

    close( m_fd );
    m_fd = -1;

    return;
}

bool FileLock::lock_retry( int count, int wait_period )
{
    bool success = false;

    while ( success == false && count > 0 ) {
        success = trylock();

        if ( success ) break;

        count--;

        int w = wait_period * ( rand() % 5 );

        waittime( w );
    }

    return success;
}
