#!/usr/bin/env perl

use strict;
use warnings;
use Template;
use File::Temp qw( tempdir );

sub MAIN {
    my $buildable_dockerfile = _get_dockerfile_template();
    my $tempdir = tempdir( CLEANUP => 1 );
    system "cp", "-a", ".", $tempdir;
    _create_dockerfile( $tempdir, $buildable_dockerfile );
    chdir $tempdir;
    my @args = @ARGV;

    if ( !( grep { /^-t$/ } @args ) && !( grep { /tag/ } @args ) ) {
        die "You might forget the name of image to be built\n";
    }

    if ( !grep { /force-rm/ } @args ) {
        unshift @args, "--force-rm";
    }

    my @command = ( "docker", "build", @args );

    if ( $ENV{DEBUG} ) {
        print "================================\n";
        printf "BUILD COMMAND >> %s\n", join " ", @command;
        print "================================\n";
    }

    system @command;
}

sub _get_dockerfile_template {
    if ( !-f "Dockerfile" ) {
        die "Dockerfile is not found.\n";
    }

    my $tt      = Template->new;
    my $content = qq{};

    $tt->process( "Dockerfile", \%ENV, \$content )
      or die $tt->error . "\n";

    return $content;
}

sub _create_dockerfile {
    my $dir     = shift;
    my $content = shift;
    open my $FILE, ">:utf8", "$dir/Dockerfile"
      or die "Unable to create buildable Dockerfile at $dir.\n";
    print $FILE $content;
    close $FILE;

    if ( $ENV{DEBUG} ) {
        print "================================\n";
        print "Output to >> $dir/Dockerfile\n";
        print "================================\n";
        print "$content\n";
    }
}

caller || MAIN();
