package file;

use File::Slurp;
use autodie;
use Carp qw/carp confess/;
use File::Path qw//;
use Data::Dump qw/dump/;

my $debug = 1;

sub mkpath {
	my $file = shift;
	my $dir = $1 if $file =~ s{(^.+)/[^/]+}{$1};
	if ( $dir && ! -d $dir ) {
		carp "# mkdir $dir";
		File::Path::mkpath $dir;
	}
}

sub append {
	my ( $file, $content ) = @_;

	if ( ! -e $file ) {
		mkpath $file;
		write_file $file, $content;
		my $size = -s $file;
		carp "## append created $size bytes in $file";
		return $size;
	}

	my $on_disk = read_file $file;

	my $relaxed_content = $content;
	   $relaxed_content =~ s{\s+}{\\s+}gs;

	if ( $on_disk !~ m{$relaxed_content} ) {

#		$content =~ s{^[\n\r]+}{\n}s;
#		$content =~ s{[\n\r]*$}{\n}s;

		if ( $on_disk =~ s{([\s+]exit[\s\d]*)$}{\n$content\n$1}s ) {
#			warn "# insert $file\n$on_disk";
			write_file $file, $on_disk;
		} else {
#			warn "# append $file\n$content\n";
			open($fh, '>>', $file);
			print $fh $content;
			close($fh);
		}

		carp "## append to $file";
		return -s $file;
	}
}

sub change {
	my ( $file, $from, $to ) = @_;

	my $content = read_file $file;
	if ( $content =~ s{$from}{$to}s ) {
		write_file $file, $content;
		carp "## change $file $from => $to" if $debug;
		return 1;
	} elsif ( $content !~ m{$to}s ) {
		confess "can't find $from to change into $to in $file in ",dump( $content );
	}
}

sub replace {
	my ( $file, $content ) = @_;
	mkpath $file;
	write_file $file, $content;
}

sub copy_once {
	my ( $from, $to ) = @_;
	die "no destination" unless $to;
	return if -e $to;
	mkpath $to;
	my $perm = (stat $from)[2];
	carp "# copy_once $from => $to $perm";
	write_file $to, read_file($from);
	chmod $perm, $to;
}

1;
