#! /usr/bin/env perl -I./bin

use strict;
use warnings;

use Cwd 'getcwd';
use File::Copy 'copy';
use File::Copy::Recursive 'rcopy';   # CPAN
use File::Path 'remove_tree';
use File::stat 'stat';
use JSON 'encode_json', 'from_json'; # CPAN
use Readonly;                        # CPAN
use String::Util 'trim';             # CPAN
use Text::Caml;                      # CPAN
use WWW::Curl::Simple;               # CPAN

use Metabase::Util;

Readonly my $app             => artifact('Metabase.app');
Readonly my $zipfile         => artifact('Metabase.zip');
Readonly my $appcast         => artifact('appcast.xml');
Readonly my $release_notes   => artifact('release-notes.html');
Readonly my $dmg             => artifact('Metabase.dmg');

Readonly my $xcode_project   => get_file_or_die('OSX/Metabase.xcodeproj');

# Get the version saved in the CFBundle, e.g. '0.11.3.1'
sub version {
    return trim(plist_buddy_exec('Print', 'CFBundleVersion'));
}

# Get the tag saved in version.properties, e.g. '0.12.0'
sub version_from_props_file {
  open(FILE, get_file_or_die('resources/version.properties')) or die $!;
  while (<FILE>) { m/^tag/ && s/^tag=v([0-9.]+)[^0-9.]*$/$1/ && (return trim($_)); };
}

# This is the name of the subdirectory on s3, e.g. 'v.0.12.0'
sub upload_subdir {
  return 'v' . version_from_props_file();
}

# Next version after version(), e.g. '0.11.3.2'
sub next_version {
    my ($old_version_tag, $old_version_point_release) = (version() =~ /^(\d+\.\d+\.\d+)\.(\d+)$/);

    Readonly my $tag_from_props_file => version_from_props_file();

    # Now calculate the new version, which is ($tag.$point_release)
    # Check and see if tag has changed in version.properties; if so, new version is the first "point release" of that tag.
    return $old_version_tag eq $tag_from_props_file ? ($old_version_tag . '.' . ($old_version_point_release + 1)) : "$tag_from_props_file.0";
}

sub bump_version {
    Readonly my $new_version => next_version();
    announce 'Bumping version: ' . version() . " -> $new_version";

    plist_buddy_exec('Set', ':CFBundleVersion', $new_version);
    plist_buddy_exec('Set', ':CFBundleShortVersionString', $new_version);
}

sub clean {
    system('xcodebuild', 'clean', '-project', $xcode_project) == 0 or die $!;
    remove_tree(OSX_ARTIFACTS_DIR);
}

# Build Metabase.app
sub build {
    announce "Building $app...";

    Readonly my $xcarchive => artifact('Metabase.xcarchive');

    # remove old artifacts if they exist
    remove_tree($xcarchive, $app);

    # Build the project and generate Metabase.xcarchive
    system('xcodebuild',
           '-project', $xcode_project,
           '-scheme', 'Metabase',
           '-configuration', 'Release',
           '-archivePath', $xcarchive,
           'archive') == 0 or die $!;

    # Ok, now create the Metabase.app artifact
    system('xcodebuild',
           '-exportArchive',
           '-exportFormat', 'APP',
           '-archivePath', $xcarchive,
           '-exportPath', $app) == 0 or die $!;

    # Ok, we can remove the .xcarchive file now
    remove_tree($xcarchive);
}

# Codesign Metabase.app
sub codesign {
    my $codesigning_cert_name = config('codesigningIdentity') or return;

    announce "Codesigning $app...";

    system('codesign', '--force', '--verify',
           '--sign', $codesigning_cert_name,
           '-r=designated => anchor trusted',
           '--deep', get_file_or_die($app)) == 0 or die "Code signing failed: $!\n";
}

# Verify that Metabase.app was signed correctly
sub verify_codesign {
    return unless config('codesigningIdentity');

    announce "Verifying codesigning for $app...";

    system('codesign', '--verify', '--deep', '--display',
           '--verbose=4', get_file_or_die($app)) == 0 or die "Code signing verification failed: $!\n";

    # Double-check with System Policy Security tool
    system('spctl', '--assess', '--verbose=4', get_file_or_die($app)) == 0
}


# ------------------------------------------------------------ PACKAGING FOR SPARKLE ------------------------------------------------------------

# Create ZIP containing Metabase.app
sub archive {
    announce "Creating $zipfile...";

    remove_tree($zipfile);

    get_file_or_die($app);

    system('cd ' . OSX_ARTIFACTS_DIR . ' && zip -r Metabase.zip Metabase.app') == 0 or die $!;
    get_file_or_die($zipfile);
}

sub generate_signature {
    Readonly my $private_key_file => getcwd() . '/OSX/dsa_priv.pem';

    unless (-e $private_key_file) {
        warn "Missing private key file: $private_key_file\n";
        return;
    }

    Readonly my $sign_update_script => get_file_or_die('bin/lib/sign_update.rb');

    get_file_or_die($zipfile);

    return trim(`$sign_update_script "$zipfile" "$private_key_file"`);
}

# Generate the appcast.xml RSS feed file that Sparkle reads to check for updates
sub generate_appcast {
    announce "Generating $appcast...";

    remove_tree($appcast);

    my $aws_bucket  = config('awsBucket')  or return;
    my $signature   = generate_signature() or return;

    open(my $out, '>', $appcast) or die "Unable to write to $appcast: $!";
    print $out Text::Caml->new->render_file(get_file_or_die('bin/templates/appcast.xml.template'), {
        VERSION   => version(),
        SIGNATURE => $signature,
        LENGTH    => stat(get_file_or_die($zipfile))->size,
        S3_BUCKET => $aws_bucket,
        S3_SUBDIR => upload_subdir()
    });
    close $out;
}

sub edit_release_notes {
    remove_tree($release_notes);

    copy(get_file_or_die('bin/templates/release-notes.html.template'), $release_notes) or die $!;
    system('emacs', '-nw', get_file_or_die($release_notes)) == 0 or die $!;
}


# ------------------------------------------------------------ CREATING DMG ------------------------------------------------------------

sub create_dmg_from_source_dir {
    my ($source_dir, $dmg_filename) = @_;
    announce "Creating DMG: $dmg_filename from source $source_dir...";

    system('hdiutil', 'create',
           '-srcfolder', $source_dir,
           '-volname', 'Metabase',
           '-fs', 'HFS+',
           '-fsargs', '-c c=64,a=16,e=16',
           '-format', 'UDRW',
           '-size', '256MB',          # it looks like this can be whatever size we want; compression slims it down
           $dmg_filename) == 0 or die $!;
}

# Mount the disk image, return the device name
sub mount_dmg {
    my ($dmg_filename) = @_;
    announce "Mounting DMG...";

    my $device = `hdiutil attach -readwrite -noverify -noautoopen $dmg_filename`;
    # Find the device name: the part of the output looks like /dev/disk11
    for my $token (split(/\s+/, $device)) {
        if ($token =~ m|^/dev/|) {
            $device = $token;
            last;
        }
    }

    announce "Mounted $dmg_filename at $device";
    return $device;
}

sub dmg_add_applications_shortcut {
    announce "Adding shortcut to /Applications...";

    system('osascript', '-e',
           'tell application "Finder"
              tell disk "Metabase"
                open
                set current view of container window to icon view
                set toolbar visible of container window to false
                set statusbar visible of container window to false
                set the bounds of container window to {400, 100, 885, 430}
                set theViewOptions to the icon view options of container window
                set arrangement of theViewOptions to not arranged
                set icon size of theViewOptions to 72
                make new alias file at container window to POSIX file "/Applications" with properties {name:"Applications"}
                set position of item "Metabase.app" of container window to {100, 100}
                set position of item "Applications" of container window to {375, 100}
                update without registering applications
                delay 5
                close
              end tell
           end tell') == 0 or die $!;
}

sub finalize_dmg {
    my ($device, $dmg_filename) = @_;
    announce "Finalizing DMG...";

    # Remove any hidden files that creeped into the DMG
    remove_tree('/Volumes/Metabase/.Trashes',
                '/Volumes/Metabase/.fseventsd');


    # Set DMG permissions, force completion of pending disk writes
    system('chmod', '-Rf', 'go-w', '/Volumes/Metabase') == 0 or warn $!; # this might issue warnings about not being able to affect .Trashes
    system('sync');
    system('sync');

    # unmount the temp DMG
    announce "Unmounting $device...";
    system('hdiutil', 'detach', $device) == 0 or die $!;

    # compress the DMG
    announce "Compressing DMG...";
    system('hdiutil', 'convert', $dmg_filename,
           '-format', 'UDZO',
           '-imagekey', 'zlib-level-9',
           '-o', $dmg) == 0 or die $!;
}

sub create_dmg {
    announce "Preparing DMG files...";

    # detach any existing Metabase DMGs
    system('hdiutil', 'detach', '/Volumes/Metabase') if -d '/Volumes/Metabase';

    Readonly my $temp_dmg       => artifact('Metabase.temp.dmg');
    Readonly my $dmg_source_dir => artifact('dmg');

    # Clean up old artifacts
    remove_tree($dmg_source_dir, $temp_dmg, $dmg);
    mkdir $dmg_source_dir or die $!;

    # Copy Metabase.app into the source dir
    rcopy(get_file_or_die($app), $dmg_source_dir . '/Metabase.app') or die $!;

    # Ok, now proceed with the steps to create the DMG
    create_dmg_from_source_dir($dmg_source_dir, $temp_dmg);

    Readonly my $device => mount_dmg($temp_dmg);

    dmg_add_applications_shortcut;

    finalize_dmg($device, $temp_dmg);

    announce "DMG created successfully: $dmg";

    # Cleanup: remove temp file & temp dir
    remove_tree($temp_dmg, $dmg_source_dir);
}


# ------------------------------------------------------------ UPLOADING ------------------------------------------------------------

sub announce_on_slack {
    Readonly my $slack_url => config('slackWebhookURL') or return;
    Readonly my $version   => version();
    Readonly my $awsURL    => 'https://s3.amazonaws.com/' . config('awsBucket') . '/' . upload_subdir() . '/Metabase.dmg';
    my $text = "Metabase OS X $version 'Tumultuous Toucan' Is Now Available!\n\n" .
               "Get it here: $awsURL\n\n";

    open(my $file, get_file_or_die($release_notes)) or die $!;
    while (<$file>) {
        m/^\s+<li>.*$/ && s|^\s+<li>(.*)</li>$|$1| && ($text .= '*  ' . $_);
    }

    my $json = encode_json {
        channel    => '#general',
        username   => 'OS X Bot',
        icon_emoji => ':bird:',
        text       => trim($text)
    };

    my $curl = WWW::Curl::Simple->new;
    unless ((my $response = $curl->post($slack_url, $json))->code == 200) {
        die 'Error posting to slack: ' . $response->code . ' ' . $response->content . "\n";
    }
}

# Upload artifacts to AWS
# Make sure to run `aws configure --profile metabase` first to set up your ~/.aws/config file correctly
sub upload {
    my $aws_profile = config('awsProfile') or return;
    my $aws_bucket  = config('awsBucket')  or return;

    # Make a folder that contains the files we want to upload
    Readonly my $upload_dir => artifact('upload');
    remove_tree($upload_dir) if -d $upload_dir;
    mkdir $upload_dir or die $!;

    # appcast.xml goes in the root directory
    copy(get_file_or_die($appcast), $upload_dir) or die $!;

    # zipfile, release notes, and DMG go in a dir like v0.12.0
    Readonly my $upload_subdir => $upload_dir . '/' . upload_subdir();
    mkdir $upload_subdir or die $!;

    for my $file ($zipfile, $release_notes, $dmg) {
      copy(get_file_or_die($file), $upload_subdir) or die $!;
    }

    announce "Uploading files to $aws_bucket...";
    system('aws', '--recursive',
           '--profile', $aws_profile,
           '--region', 'us-east-1',
           's3', 'cp', $upload_dir,
           "s3://$aws_bucket") == 0 or die "Upload failed: $!\n";

    announce_on_slack;

    announce "Upload finished."
}


# ------------------------------------------------------------ RUN ALL ------------------------------------------------------------

sub all {
    clean;
    bump_version;
    build;
    codesign;
    verify_codesign;
    archive;
    generate_appcast;
    edit_release_notes;
    create_dmg;
    upload;
}

# Run all the commands specified in command line args, otherwise default to running 'all'
@ARGV = ('all') unless @ARGV;
no strict 'refs';
map { $_->(); } @ARGV;

print_giant_success_banner();