<?php
include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
/**
 * Core Upgrader class for WordPress. It allows for WordPress to upgrade itself in combiantion with the wp-admin/includes/update-core.php file
 *
 * @TODO More Detailed docs, for methods as well.
 *
 * @package WordPress
 * @subpackage Upgrader
 * @since 2.8.0
 */
class Xpress_Upgrader extends WP_Upgrader {

	function upgrade_strings() {
		$this->strings['up_to_date'] = __('XPressME Integration Kit is at the latest version.');
		$this->strings['no_package'] = __('Upgrade package not available.');
		$this->strings['downloading_package'] = __('Downloading update from <span class="code">%s</span>&#8230;');
		$this->strings['unpack_package'] = __('Unpacking the update&#8230;');
		$this->strings['copy_failed'] = __('Could not copy files.');
		$this->strings['make_config'] = __('Delete source wp-config.php.');
		$this->strings['delete_failed'] = __('Could not delete files.');
	}

	function upgrade($current) {
		global $wp_filesystem;

		$this->init();
		$this->upgrade_strings();

		if ( !empty($feedback) )
			add_filter('update_feedback', $feedback);

		// Is an update available?
		if ( !isset( $current->response ) || $current->response == 'latest' )
			return new WP_Error('up_to_date', $this->strings['up_to_date']);

		$res = $this->fs_connect( array(ABSPATH, WP_CONTENT_DIR) );
		if ( is_wp_error($res) )
			return $res;

		$wp_dir = trailingslashit($wp_filesystem->abspath());

		$download = $this->download_package( $current->package );
		if ( is_wp_error($download) )
			return $download;

		$working_dir = $this->unpack_package( $download );
		if ( is_wp_error($working_dir) )
			return $working_dir;
		$subdirs = $wp_filesystem->dirlist($working_dir,false);
		foreach($subdirs as $subdir){
			$subdir_name = $subdir['name'];
		}
		
		$kit_dir = $working_dir .'/' .$subdir_name .'/xpressme_integration_kit/';
		
		// Copy update-core.php from the new version into place.
		$update_xpress_file = 'wp-content/plugins/xpressme/include/update_xpress.php';
//		if ( !$wp_filesystem->copy($kit_dir . $update_xpress_file, $wp_dir . $update_xpress_file, true) ) {
//			$wp_filesystem->delete($working_dir, true);
//			return new WP_Error('copy_failed', $this->strings['copy_failed']);
//		}
		$wp_filesystem->chmod($wp_dir . $update_xpress_file, FS_CHMOD_FILE);

		require(ABSPATH . $update_xpress_file);

		return update_xpress($kit_dir, $wp_dir);
		
	// Remove working directory
		$wp_filesystem->delete($working_dir, true);
		if ( !$wp_filesystem->delete($working_dir, true)){
			return new WP_Error('delete_failed', $this->strings['delete_failed']);
		}
		show_message( __('Delete Working directory') );
		$wp_filesystem->chmod($wp_dir . 'templates/', 0777);
	}
}

