#!/usr/local/bin/perl
# ==================================================================
# Links SQL - enhanced directory management system
#
#   Website  : http://gossamer-threads.com/
#   Support  : http://gossamer-threads.com/scripts/support/
#   Revision : $Id: nph-imageresize.cgi,v 1.2 2004/12/09 00:55:04 aki Exp $
# 
# Copyright (c) 2001 Gossamer Threads Inc.  All Rights Reserved.
# Redistribution in part or in whole strictly prohibited. Please
# see LICENSE file for full details.
# ==================================================================
    use lib '/var/home/slowtwitch/slowtwitch.com/cgi-bin/articles/admin';

    use strict;
    use vars  qw/$USE_HTML/;
    use Links qw/$IN $DB $CFG/;
    use Links::Plugins;
    use Plugins::ConvertVideo;
    use GT::TempFile;
    use GT::SQL::File;

    $| = 1;
    Links::init('/var/home/slowtwitch/slowtwitch.com/cgi-bin/articles/admin');

    main();

sub main {
# --------------------------------------------------
    $USE_HTML       = exists $ENV{REQUEST_METHOD} ? 1 : 0;
    local $SIG{__DIE__} = \&Links::fatal if $USE_HTML;

    my $links = $DB->table( 'Links' ) or die $GT::SQL::error;

# Beautify output...
    my $lcount = $links->count;
    if ( $USE_HTML ) {
        print qq~
        <html>
            <head>
                <title>Converting video database</title>
            </head>
            <body bgcolor="white">
        ~;
        print Links::header ('Updating Links ...', 'Links SQL is now attempting to update your $lcount links, please be patient, this can take a while.', 0);
        print '<pre>';
    }
    else {
        print "\nUpdating $lcount links\n\n";
    }

    my $cfg = Links::Plugins::get_plugin_user_cfg('ConvertVideo');
    my $vf_field = $cfg->{video_file_field};
    my $ff_field = $cfg->{flash_file_field};
    my $thumb  = $cfg->{thumbnail_file_field};

# Now do it. This is the really slow part.
    $links->select_options( "order by ID" );
    my $link_handle = $links->select([ 'ID', $vf_field ], { Link_Type => 'video' } ) or die $GT::SQL::error;

    my $i = 1;
    while ( my $link = $link_handle->fetchrow_hashref ) {
        my $source_path = $links->file_info( $vf_field, $link->{ID} ) or do {
            warn "Could not fetch file for link $link->{ID} '$GT::SQL::error'\n";
            next;
        };
        Plugins::ConvertVideo::convert_video($link);

        print $link->{ID} . ( $link->{$ff_field} ? "*" : "" ) . " ";
        $i++ % 10 or print "\n";
        my $id = $link->{ID};
        delete $link->{ID};

        $links->update( $link, { ID => $id } ) or do {
            warn "Could not update link $link->{ID} '$GT::SQL::error'\n";
            next;
        };
    }

# End beautiful output
    if ($USE_HTML) {
        print "\nDone!</pre></body></html>\n\n";
    }
    else {
        print "\n\nDone!\n"
    }
}

1;