#!/usr/bin/perl

use warnings;
use strict;

use lib "/var/www/iblech/dnsx";
use Imager;
use Getopt::Long;
use DNSX::BitFH;

GetOptions(
  "input=s"  => \my $input,
  "output=s" => \my $output,
  "mode=s"   => \my $mode,
);

die unless $mode =~ /^(embed|extract)$/;

# besser machen hierda
die unless -R $input;

my $img = Imager->new;
$img->open(file => $input, type => "png");

my ($height, $width) = ($img->getheight, $img->getwidth);

if($mode eq "embed") {
  my $iter = DNSX::BitFH::Input->new(\*STDIN);
  my $i = 0;
  while(defined( my $databit = $iter->next )) {
    my $channel = $i % 3;
    my $pos = int($i / 3);
    my $y   = int($pos / $width);
    my $x   = $pos % $width;

    die if $pos > $height * $width;

    my $color = $img->getpixel(x => $x, y => $y);
    my @rgb   = $color->rgba;
    $rgb[$channel] = 2*int($rgb[$channel] / 2) + $databit; # ($rgb[$channel] | 1) ^ $databit; 
    $color->set(@rgb);

    $img->setpixel(x => $x, y => $y, color => $color);
    warn "$i -> $x,$y, $channel: $databit -> $rgb[$channel]\n";

    $i++;
  }

  $img->write(file => $output);
} else {
  my $bitfh = DNSX::BitFH::Output->new(\*STDOUT);

  for my $y (0..$height - 1) {
    for my $x (0..$width - 1) {
      my @rgb = $img->getpixel(x => $x, y => $y)->rgba;
      for my $color ((@rgb)[0..2]) {
	warn "$x,$y: $color -> " . (($color % 2 == 0) ? 0 : 1);
	$bitfh->add($color % 2 == 0 ? 0 : 1);
      }
    }
  }

  $bitfh->flush() or die;
}
