<?php

set_time_limit(0);
date_default_timezone_set('UTC');

if (defined('STDIN')) {
    // COMMAND LINE execution
    $photoFilename = $argv[1];
    $captionText = $argv[2];
    $username = $argv[3];
    $password = $argv[4];
    $debug = $argv[5];
    $truncatedDebug = $argv[6];
    $proxyUser = $argv[7];
    $proxyPassword = $argv[8];
    $proxyIP = $argv[9];
    $proxyPort = $argv[10];
    $autoload = $argv[11];
} else {
    exit(0); // EXIT IF EXECUTED BY WEBSERVER
}

if (isset($photoFilename, $captionText, $username, $password, $debug, $truncatedDebug, $proxyUser, $proxyPassword, $proxyIP, $proxyPort, $autoload)) {
    echo "Received:\n\t$captionText\n\t$photoFilename\n\t$username\n\t$password\n\t$debug\n\t$truncatedDebug\n\t$proxyUser\n\t$proxyPassword\n\t$proxyIP\n\t$proxyPort\n\t$autoload\n\n";
    echo "All arguments defined. Continuing...\n";
}
else {
    echo "Error: Not all arguments defined. Exiting.\n";
    exit(0);
}

// require '/home/pi/instafeed/vendor/autoload.php';
// require __DIR__.'/../vendor/autoload.php';
require($autoload);

$ig = new \InstagramAPI\Instagram($debug, $truncatedDebug);
$ig->setProxy("http://$proxyUser:$proxyPassword@$proxyIP:$proxyPort"); // SOCKS5 Proxy needing authentication
try {
    $ig->login($username, $password);
} catch (\Exception $e) {
    echo 'Error: '.$e->getMessage()."\n";
    exit(0);
}

try {
    // The most basic upload command, if you're sure that your photo file is
    // valid on Instagram (that it fits all requirements), is the following:
    // $ig->timeline->uploadPhoto($photoFilename, ['caption' => $captionText]);

    // However, if you want to guarantee that the file is valid (correct format,
    // width, height and aspect ratio), then you can run it through our
    // automatic photo processing class. It is pretty fast, and only does any
    // work when the input file is invalid, so you may want to always use it.
    // You have nothing to worry about, since the class uses temporary files if
    // the input needs processing, and it never overwrites your original file.
    //
    // Also note that it has lots of options, so read its class documentation!
    $photo = new \InstagramAPI\Media\Photo\InstagramPhoto($photoFilename);
    $ig->timeline->uploadPhoto($photo->getFile(), ['caption' => $captionText]);
} catch (\Exception $e) {
    echo 'Error: '.$e->getMessage()."\n";
}
