#!/usr/bin/env perl

use strict;
use warnings;

my ($file, $sizes, $faviconDir) = @ARGV;

die "usage: $0 [origfile] [sizes] [faviconDir]   (sizes is ,-seperated list of side length or short, medium or long\n" unless defined $file and defined $sizes and defined $faviconDir;

die "File '$file' not found!\n" unless -e $file;

$sizes = '16,32' if 'short' eq $sizes;
$sizes = '16,32,48,64,128,256' if 'medium' eq $sizes;
$sizes = '16,32,48,64,128,192,228,230,256,512' if 'long' eq $sizes;

my @sizes = split m/,/, $sizes;

my $include = "";

mkdir($faviconDir);
my $dir = undef;
opendir($dir, $faviconDir) or die "Could not read directory '$faviconDir', because: $!\n";
while(my $fn = readdir($dir)) {
  unlink("$faviconDir/$fn") if -d "$faviconDir/$fn"
}
for my $s(@sizes) {
  resize($s, "favicon-${s}x$s.png");
}

resize(180, "apple-touch-icon.png");

sub resize {
  my ($size, $newfile) = @_;
  my $ret = system("convert '$file' -resize '${size}x$size' '$faviconDir/$newfile'");
  die "$0: convert exited with error code $ret on generating '$faviconDir/$newfile'\n" if $ret;
  die "$0: output file '$faviconDir/$newfile' could not be generated\n" unless -e "$faviconDir/$newfile";
  my $icon = "icon";
  $icon = "apple-touch-icon" if $newfile=~m#apple#;
  $include .= qq#<link rel="$icon" sizes="${size}x$size" href="/$newfile">#
}

my $wh = undef;
open($wh, '>', "$faviconDir/include.html") or die "Could not write '$faviconDir/include.html', because: $!";
print $wh $include;


