/************************************************/
/* uploadToGoogleDrive.php                      */
/* $argv[1]: アップロード先のフォルダ名         */
/* $argv[2]: アップロードするファイルパス       */
/************************************************/ 
require_once("./autoload.php");
define('APPLICATION_NAME', 'DBBackupSample');
define('CREDENTIALS_PATH', __DIR__ . '/dbbackup-XXXXXXXXXXXX.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');

// ScopeをDRIVE_FILEに設定する
define('SCOPES', implode(' ', array(
        Google_Service_Drive::DRIVE)
));

if (php_sapi_name() != 'cli') {
    throw new Exception('This application must be run on the command line.');
}


/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient() {
    $client = new Google_Client();
    $client->setApplicationName(APPLICATION_NAME);
    $client->setScopes(SCOPES);
    $client->setAuthConfig(CLIENT_SECRET_PATH);
    $client->setAccessType('offline');

    // Load previously authorized credentials from a file.
    //echo CREDENTIALS_PATH;
    $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
    $accessToken = json_decode(file_get_contents($credentialsPath), true);

    $client->setAccessToken($accessToken);

    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
      //print "expired==>\n";
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
    }
    return $client;
}


/**
 * Expands the home directory alias '~' to the full path.
 * @param string $path the path to expand.
 * @return string the expanded path.
 */
function expandHomeDirectory($path) {
    $homeDirectory = getenv('HOME');
    if (empty($homeDirectory)) {
        $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
    }
    return str_replace('~', realpath($homeDirectory), $path);
}


// 引数の確認
$client = getClient();
$filePath = trim($argv[2]);
$folderName = trim($argv[1]);
printf("=============================================\n");
printf("Start Script:%s\n", date("Y-m-d h:m:s"));
printf("Save FilePath To Google Drive=>%s\n", $filePath);
printf("Save Folder In Google Drive=>%s\n", $folderName);

if (file_exists($filePath)) {
} else {
    die("$filepath は存在しません");
    exit();
}

$path_parts = pathinfo($filePath);
$fileName = $path_parts['basename'];

$driveService = new Google_Service_Drive($client);

// Google DriveのフォルダIDを取得
$result = $driveService->files->listFiles(array(
        'q' => "mimeType='application/vnd.google-apps.folder'",
        'q' => "name='$folderName'",
    ));
$folderId = "";

foreach ( $result->getFiles() as $file) {
    assert($file instanceof \Google_Service_Drive_DriveFile);
    $name = $file->name;
    if ($name == $folderName){
      $folderId = $file->id;
      break;
    }
}

if ($folderId == ""){
  try{
      // フォルダが存在しなければフォルダを新規作成する
      $fileData = array();
      $fileData['name'] = $folderName;
      $fileData['mimeType'] = 'application/vnd.google-apps.folder';

	  // ここではroot直下に作成、 ここで親フォルダのIDを指定すれば、そこの配下に作れる
      $fileData['parents'][] = 'root';

      $fileMetadata = new Google_Service_Drive_DriveFile($fileData);
      $file = $driveService->files->create($fileMetadata,['fields'=>'id,name,parents']);
      $folderId = $file->id;
      printf("New Folder Created: ID:%s Name:%s parent ID:%s", $file->id, $file->name, $file->parents[0]);
  } catch (Google_Service_Exception $e) {
      print $e->getMessage();

  } catch (\Google_Exception $e) {
      print $e->getMessage();
  }
}

// アップロードするGoogle DriveのフォルダのIDを指定する
$fileMetadata = new Google_Service_Drive_DriveFile(array(
                'name' => $fileName,
                'parents' => array($folderId)
        ));

// アップロードするファイルのMIMEタイプを取得する
$mime = mime_content_type($filePath);

try {
    $content = file_get_contents($filePath);
    $file = $driveService->files->create($fileMetadata, array(
            'data' => $content,
          'mimeType' => $mime,
//          'mimeType' => 'application/x-gzip',
            'uploadType' => 'multipart',
            'fields' => 'id'));
    print "File '$fileName' uploaded with id '$file->id'" . PHP_EOL;
}
catch (Exception $exc) {
    print "Error working with file '$fileName':" . $exc->getMessage();
}