#!/usr/local/php/bin/php
<?php
/**
 *	Project:	Quicty: Quick application build environment depends on PEAR and Smarty
 *	File:		qt_add_page
 *
 *	@copyright	Tomoyuki Negishi and ZubaPitaTech, Inc.
 *	@author		Tomoyuki Negishi <tomoyu-n@zubapita.jp>
 *	@license	http://www.opensource.org/licenses/bsd-license.php The BSD License
 *	@package	Quicty
 *	@version	$Id:$
 */

require_once 'myQuicty.php';

// {{{ qt_add_page
/**
 *	qt_add_page class
 *
 *	@author		Tomoyuki Negishi <tomoyu-n@zubapita.jp>
 *	@access		public
 *	@package	Quicty
 */
class qt_add_page extends myQuicty {

	function dispatch_index() {
		$this->left_delimiter = '<!--{';
		$this->right_delimiter = '}-->';
		$this->compile_dir = '/tmp';
		umask(0);
		if(!file_exists($this->compile_dir)) mkdir($this->compile_dir);
		//require_once $home_dir.'/etc/conf/conf_values.conf';
		if(!$_ENV['QUICTY_MOD']) die("Did not define enviroment var 'QUICTY_MOD'.\n");
		if($_ENV['windir']) $_ENV['PWD'] = `echo %CD%`;
		echo "Your current dir is "; print_r($_ENV['PWD']); echo "\n";
		if(!file_exists('lib/myQuicty.php')) 
			die("You don't have file 'lib/myQuicty.php'.");
		if(!file_exists('htdocs/index.php'))
			die("You don't have file 'htdocs/index.php'.");
		if(!file_exists('lib/Pages'))
			die("You don't have dir 'lib/Pages'.");
		if(!file_exists('view')) 
			die("You don't have dir 'view'.");
		$argv = get_argv();
		$page_name = $argv['name'];
		$page_title = $argv['title'];
		$level = $argv['level'];
		$page_type = $argv['page'];

		$page_kind = array(
					1=>array('desc'=>"Single Level(No subdir) - Single Page",'level'=>'single','page'=>'single'),
					2=>array('desc'=>"Single Level(No subdir) - Multi Page",'level'=>'single','page'=>'multi'),
					3=>array('desc'=>"Dual Level - Single Page",'level'=>'dual','page'=>'single'),
					4=>array('desc'=>"Dual Level - Multi Page",'level'=>'dual','page'=>'multi'),
					5=>array('desc'=>"Triple Level - Single Page",'level'=>'triple','page'=>'single'),
					6=>array('desc'=>"Triple Level - Multi Page",'level'=>'triple','page'=>'multi'),
					7=>array('desc'=>"Upload Page(Dual/Single Page)",'level'=>'dual','page'=>'upload'),
					8=>array('desc'=>"Upload Page(Triple/Single Page)",'level'=>'triple','page'=>'upload'),
					);
		$use_template = array(
					1=>array('source'=>array(1=>'view/single/index.html'),
							'target'=>array(1=>'view/index.html')),
					2=>array('source'=>array(1=>'view/multi/index.html','view/multi/info.html'),
							'target'=>array(1=>'view/index.html','view/info.html')),
					3=>array('source'=>array(1=>'view/multi_single/index.html'),
							'target'=>array(1=>'view/%page%/index.html')),
					4=>array('source'=>array(1=>'view/multi/index.html','view/multi/info.html'),
							'target'=>array(1=>'view/%page%/index.html','view/%page%/info.html')),
					5=>array('source'=>array(1=>'view/multi_single/index.html'),
							'target'=>array(1=>'view/%subdir%/%page%/index.html')),
					6=>array('source'=>array(1=>'view/multi/index.html','view/multi/info.html'),
							'target'=>array(1=>'view/%subdir%/%page%/index.html','view/%subdir%/%page%/info.html')),
					7=>array('source'=>array(1=>'view/multi/info.html'),
							'target'=>array(1=>'view/%page%/add.html')),
					8=>array('source'=>array(1=>'view/multi/info.html'),
							'target'=>array(1=>'view/%subdir%/%page%/add.html')),
					);
		$use_class = array(
					1=>array('source'=>array(
								1=>'lib/Pages/index.class.tpl',
								2=>'lib/Pages/page.options.tpl'
								),
							'target'=>array(
								1=>'lib/Pages/index.class.php',
								2=>'lib/Pages/index.options.php'
								)
							),
					2=>array('source'=>array(
								1=>'lib/Pages/page.class.tpl',
								2=>'lib/Pages/page.options.tpl'
								),
							'target'=>array(
								1=>'lib/Pages/index.class.php',
								2=>'lib/Pages/index.options.php'
								)
							),
					3=>array('source'=>array(
								1=>'lib/Pages/index.class.tpl',
								2=>'lib/Pages/page.options.tpl'
								),
							'target'=>array(
								1=>'lib/Pages/%page%.class.php',
								2=>'lib/Pages/%page%.options.php'
								)
							),
					4=>array('source'=>array(
								1=>'lib/Pages/page.class.tpl',
								2=>'lib/Pages/page.options.tpl'
								),
							'target'=>array(
								1=>'lib/Pages/%page%.class.php',
								2=>'lib/Pages/%page%.options.php'
								)
							),
					5=>array('source'=>array(
								1=>'lib/Pages/index.class.tpl',
								2=>'lib/Pages/page.options.tpl'
								),
							'target'=>array(
								1=>'lib/Pages/%subdir%/%page%.class.php',
								2=>'lib/Pages/%subdir%/%page%.options.php'
								)
							),
					6=>array('source'=>array(
								1=>'lib/Pages/page.class.tpl',
								2=>'lib/Pages/page.options.tpl'
								),
							'target'=>array(
								1=>'lib/Pages/%subdir%/%page%.class.php',
								2=>'lib/Pages/%subdir%/%page%.options.php'
								)
							),
					7=>array('source'=>array(
								1=>'lib/Pages/upload.class.tpl'
								),
							'target'=>array(
								1=>'lib/Pages/%page%.class.php'
								)
							),
					8=>array('source'=>array(
								1=>'lib/Pages/upload.class.tpl'
								),
							'target'=>array(
								1=>'lib/Pages/%subdir%/%page%.class.php'
								)
							),
					);
		$page_types = array(1=>'single',2=>'multi',3=>'upload');
		$level_types = array(1=>'single',2=>'dual',3=>'triple');

		$reverse_map = array(
					'single'=>array('single'=>1,'multi'=>2),
					'dual'=>array('single'=>3,'multi'=>4,'upload'=>7),
					'triple'=>array('single'=>5,'multi'=>6,'upload'=>8)
					);

		echo "add new quicty page and esource..\n";
		if(in_array($level,$level_types) and in_array($page_type,$page_types)) {
			$type_no = $reverse_map[$level][$page_type];
		}
		while(!in_array($level,$level_types) or !in_array($page_type,$page_types)) {
			foreach($page_kind as $key=>$type) {
				printf("%3s: %s\n",$key,$type['desc']);
			}
			$type_no = input_tty("Select add page type No.:",false);
			if(array_key_exists($type_no,$page_kind)) {
				$level = $page_kind[$type_no]['level'];
				$page_type = $page_kind[$type_no]['page'];
			} else {
				echo "Don't exists page type!\n";
				continue;
			}
			echo "level=$level / page_type=$page_type\n";
		}
		echo "\nAdd ".$page_kind[$type_no]['desc'].".\n";

		if($page_name) $page_name = trim_slash($page_name);
		while(!$page_name or (strpos($page_name,'/')>0 and $level!='triple')) {
			if(strpos($page_name,'/')>0 and $level!='triple')
				echo "Single / Dual Level can't use sub directory.\n";
			$page_name = trim_slash(input_tty("\nInput new page name:"));
		}
		echo "\nNew page name is '$page_name'\n";

		if($page_title) $page_title = trim_slash($page_title);
		while(!$page_title) {
			$page_title = trim_slash(input_tty("\nInput new page title:",'Are you sure?[y/n]:',true,false));
		}
		echo "\nNew page title is '$page_title'\n";

		if(strpos($page_name,'/')>0) {
			list($sub_dir,$page_name) = explode('/',$page_name);
		} else {
			$sub_dir = NULL;
		}

		$use_value = array(
					1=>array('class'=>'index','dir'=>'','page'=>$page_name,'title'=>$page_title,'data'=>$page_name),
					2=>array('class'=>'index','dir'=>'','page'=>$page_name,'title'=>$page_title,'data'=>$page_name),
					3=>array('class'=>$page_name,'dir'=>"/$page_name",'page'=>$page_name,'title'=>$page_title,'data'=>$page_name),
					4=>array('class'=>$page_name,'dir'=>"/$page_name",'page'=>$page_name,'title'=>$page_title,'data'=>$page_name),
					5=>array('class'=>$page_name,'dir'=>"/$sub_dir/$page_name",'page'=>$page_name,'title'=>$page_title,'data'=>$page_name),
					6=>array('class'=>$page_name,'dir'=>"/$sub_dir/$page_name",'page'=>$page_name,'title'=>$page_title,'data'=>$page_name),
					7=>array('class'=>$page_name,'dir'=>"/$page_name",'page'=>$page_name,'title'=>$page_title,'data'=>$page_name),
					8=>array('class'=>$page_name,'dir'=>"/$sub_dir/$page_name",'page'=>$page_name,'title'=>$page_title,'data'=>$page_name),
					);

		// set subdir
		switch($level) {
			case 'single':
				$view_dir = 'view';
				$lib_dir = 'lib/Pages';
				break;
			case 'dual':
				$view_dir = 'view/'.$page_name;
				make_dir($view_dir);
				$lib_dir = 'lib/Pages';
				break;
			case 'triple':
				make_dir('view/'.$sub_dir);
				$view_dir = 'view/'.$sub_dir.'/'.$page_name;
				make_dir($view_dir);
				$lib_dir = 'lib/Pages/'.$sub_dir;
				make_dir($lib_dir);
				break;
		}
		$this->template_dir ='';

		switch($page_type) {
			case 'upload':
				if(!is_dir('var/upload'))
					make_dir('var/upload',0777);
				break;
		}
		
		// set templates
		foreach($use_template[$type_no]['source'] as $key=>$source_file) {
			$target_file = $use_template[$type_no]['target'][$key];
			$target_file = str_replace ('%page%',$page_name,$target_file);
			if($sub_dir) $target_file = str_replace ('%subdir%',$sub_dir,$target_file);
			echo "template: ".$_ENV['QUICTY_MOD']."/$source_file -> $target_file\n";
			if(file_exists($target_file)) {
				make_dir($view_dir.'/old');
				copy_files($target_file,$view_dir.'/old');
				echo "save old file '$target_file' to '$view_dir/old/'.\n";
			}
			//$contents = file_get_contents($_ENV['QUICTY_MOD'].'/'.$source_file,1);
			$template_source_dir = file_exists('etc/modules/view') ? 'etc/modules' : $_ENV['QUICTY_MOD'];
			$contents = file_get_contents($template_source_dir.'/'.$source_file,1);
			file_write_contents($target_file,$contents);
		}
		if($page_type=='multi') {
			if(!file_exists($view_dir.'/add.html'))
				_symlink('info.html',$view_dir.'/add.html');
			if(!file_exists($view_dir.'/edit.html'))
				_symlink('info.html',$view_dir.'/edit.html');
			if(!file_exists($view_dir.'/delete.html'))
				_symlink('info.html',$view_dir.'/delete.html');
		} elseif($page_type=='single') {
			if(!file_exists($view_dir.'/edit.html'))
				_symlink('index.html',$view_dir.'/edit.html');
			if(!file_exists($view_dir.'/delete.html'))
				_symlink('index.html',$view_dir.'/delete.html');
		}
		
		// set class module
		$this->assign('class_name',$use_value[$type_no]['class']);
		$this->assign('dir_name',$use_value[$type_no]['dir']);
		$this->assign('page_name',$use_value[$type_no]['page']);
		$this->assign('page_title',$use_value[$type_no]['title']);
		$this->assign('data_name',$use_value[$type_no]['data']);
		foreach($use_class[$type_no]['source'] as $key=>$source_file) {
			$target_file = $use_class[$type_no]['target'][$key];
			$target_file = str_replace ('%page%',$page_name,$target_file);
			if($sub_dir) $target_file = str_replace ('%subdir%',$sub_dir,$target_file);
			echo "class module: ".$_ENV['QUICTY_MOD']."/$source_file -> $target_file\n";
			if(file_exists($target_file)) {
				make_dir($lib_dir.'/old');
				copy_files($target_file,$lib_dir.'/old');
				echo "save old file '$target_file' to '$lib_dir/old/'.\n";
			}
			$contents = file_get_contents($_ENV['QUICTY_MOD'].'/'.$source_file,1);
			file_write_contents($target_file,$contents);
			$contents = $this->fetch($target_file);
			file_write_contents($target_file,$contents);
		}


		// add to action_list.inc
		$base_url = '{$page.base_url}';
		switch($level) {
			case 'single':
				if($page_type=='multi') {
					$action_list = "\n".<<<EOS
		<li><a href="$base_url/add.html">$page_title 追加</a></li>
EOS;
				}
				break;
			case 'dual':
				if($page_type=='single') {
					$action_list = "\n".<<<EOS
		<li><a href="$base_url/$page_name/">$page_title</a></li>
EOS;
				} elseif($page_type=='multi') {
					$action_list = "\n".<<<EOS
		<li><a href="$base_url/$page_name/">$page_title 一覧</a></li>
		<li><a href="$base_url/$page_name/add.html">$page_title 追加</a></li>
EOS;
				} elseif($page_type=='upload') {
					$action_list = "\n".<<<EOS
		<li><a href="$base_url/$page_name/add.html">$page_title Upload</a></li>
EOS;
				}
				break;
			case 'triple':
				if($page_type=='single') {
					$action_list = "\n".<<<EOS
		<li><a href="$base_url/$sub_dir/$page_name/">$page_title</a></li>
EOS;
				} elseif($page_type=='multi') {
					$action_list = "\n".<<<EOS
		<li><a href="$base_url/$sub_dir/$page_name/">$page_title 一覧</a></li>
		<li><a href="$base_url/$sub_dir/$page_name/add.html">$page_title 追加</a></li>
EOS;
				}
				break;
		}
		if($action_list) file_write_contents('view/includes/action_list.inc',$action_list,"a");

		//-----------------------------------------------------------------------------------------------------
		// Add Data_Set
		//
		echo "\n";
		if(!confirm_tty("Do you add data_set ? [y/n] :",$override=true)) {
			echo "\ndone.\n";
			exit;
		}

		// add to data_def
		$this->dsn = array('system'=>'sqlite','dbname'=>$page_name,'dataname'=>$page_name,'title'=>$page_title,'path'=>'var/sqlite');
		$this->data_set[1] = array('name'=>'id','type'=>'id');
		if($page_type=='upload') {
			$this->data_set[2] = array('name'=>'file','type'=>'file','label'=>'ファイル','attr'=>array('size'=>'50'));
		} else{
			$this->data_set[2] = array('name'=>'name','type'=>'text','label'=>'名前','attr'=>array('size'=>'50','maxlength'=>'50'));
			$this->data_set[3] = array('name'=>'url','type'=>'url','label'=>'URL','attr'=>array('size'=>'50','maxlength'=>'128'));
		}
		$data_def = serialize(array('dsn'=>$this->dsn,'data_set'=>$this->data_set));
		file_write_contents_with_confirm('etc/data_def/'.$page_name.'.def',$data_def);

		// add to data_view
		if($page_type=='upload') {
			$data_view = <<<EOS
[id]
type=id

[file]
type=file
label=ファイル
attr=start
size=50
end_attr=true
EOS;
		} else {
			$data_view = <<<EOS
[id]
type=id

[name]
type=text
label=名前
attr=start
size=50
maxlength=50
end_attr=true

[url]
type=url
label=URL
attr=start
size=50
maxlength=128
end_attr=true
EOS;
		}
		file_write_contents_with_confirm('etc/data_view/'.$page_name.'.view.conf',$data_view);

		// add to data_set
		if($page_type!='upload') {
			$data_set = <<<EOS
[dsn]
system=sqlite
dbname=$page_name
path=var/sqlite

[bind]
name:text=$page_name.name:text
url:url=$page_name.url:text
EOS;
		file_write_contents_with_confirm('etc/data_set/'.$page_name.'.set.conf',$data_set);


		// add search_view to data_view
		if($page_type!='upload') {
			$search_view = <<<EOS
[keyword]
label=キーワード
type=text
attr=start
size=30
maxlength=50
end_attr=true

[kind]
label=種類
type=select
value=start
name=名前
url=URL
end_value=true
default_list=start
kind=1
end_default_list=true
EOS;
		}
		file_write_contents_with_confirm('etc/data_view/'.$page_name.'_search.view.conf',$search_view);



		// add to sql
		$sql = "\n".<<<EOS
drop table $page_name;
create table $page_name(
	id INTEGER PRIMARY KEY, 
	name text,
	url text
);
EOS;
			file_write_contents_with_confirm('etc/sql/sqlite/'.$page_name.'.sql',$sql);
		}

		// add init.sh to bin
		if($page_type!='upload') {
			if($_ENV['windir']) {
				$init = "\n".<<<EOS
@echo off
echo "#----------------------------------------------#"
echo "# initialize sqlite  .\var\sqlite\\$page_name"
echo "#----------------------------------------------#"
sqlite .\var\sqlite\\$page_name < .\etc\sql\sqlite\\$page_name.sql
echo done.
EOS;
				file_write_contents_with_confirm('bin/init_'.$page_name.'.bat',$init);
			} else {
				$init = "\n".<<<EOS
#!/bin/sh
echo "#----------------------------------------------#"
echo "# initialize sqlite  var/sqlite/$page_name"
echo "#----------------------------------------------#"
sqlite var/sqlite/$page_name < etc/sql/sqlite/$page_name.sql
chmod o+w var/sqlite/$page_name
echo done.
EOS;
				file_write_contents_with_confirm('bin/init_'.$page_name.'.sh',$init);
			}
			umask(0);
			chmod('bin/init_'.$page_name.'.sh',0744);
			make_dir('var/sqlite',0777);
			echo "\n* attention *\n\n";
			if($_ENV['windir']) {
				echo "You must submit 'bin\\init_$page_name.bat' before accsee from Web.\n";
			} else {
				echo "You must submit 'bin/init_$page_name.sh' before accsee from Web.\n";
			}
		}
		echo "\ndone.\n";
	}
} // end of class qt_add_page
// }}}

$quicty = new qt_add_page();
$quicty->dispatch_index();

?>
