# Copyright (c) 2004  Joshua Hoblitt
#
# $Id: Util.pm,v 1.1.1.1 2004-12-22 02:16:24 jhoblitt Exp $

package PS::IPP::IData::Util;

use strict;

our $VERSION = '0.01';

use base qw( Exporter );

use Log::Log4perl qw( :levels );
use URI;

my @symbols = qw(
    %LEVELS
    _nuke_file
    _get_file_path
    _get_filehandle
    _open_uri
    _create_empty_file
);

our @EXPORT_OK      = @symbols;
our %EXPORT_TAGS    = ( standard => [ @symbols ] );

our %LEVELS = (
    off     => $OFF,
    fatal   => $FATAL,
    error   => $ERROR,
    warn    => $WARN,
    info    => $INFO,
    debug   => $DEBUG,
    all     => $ALL,
);

sub _nuke_file {
    my $path = shift;

    die "can't unlink file $path: it's a directory" 
        if -d $path;
    die "can't unlink file $path: it doesn't exist"
        unless -e $path;
    unlink $path or die "can't unlink file $path: $!";

    return 1;
}

sub _get_file_path {
    my $uri = shift;

    my $path = URI->new( $uri )->path;

    return $path;
}

sub _get_filehandle {
    my ( $path, $flags ) = @_;

    die "can't open file $path: file doesn't exist" 
        unless -e $path;
    CORE::open( my $fh, $flags, $path )
        or die "can't open file $path: $!";

    return $fh;
}

sub _open_uri {
    my ( $uri , $flags ) = @_;

    my $path = _get_file_path( $uri );
    my $fh = _get_filehandle( $path, $flags );

    return $fh;
}

sub _create_empty_file {
    my $path = shift;

    # perl's open() can't do an O_CREAT | O_EXCL
    if ( -e $path ) {
        die "file $path already exists";
    }

    my $fh;
    unless ( open( $fh, '>', $path ) ) {
        die "can not open $path: $!";
    } 

    unless ( close( $fh ) ) {
        die "can not close $path: $!";
    }

    unless ( chmod 0664, $path ) {
        die "can not chmod $path: $!";
    }

    return $path;
}

1;

__END__
