
ad_library {

    Utility functions for Skins Application
    
    @author SriHarsha Chintalapani (sriharsha.ch@azri.biz)
}

ad_proc skin_upload {
    {-upload_file:required}
 } { 
    
   uploads the theme and put all the theme files into corresponding skins directory
   and registers the skin into the database
    
} {

    set path [ns_tmpnam]
    file mkdir $path
    set upload_files [list [template::util::file::get_property filename $upload_file]]
    set upload_tmpfiles [list [template::util::file::get_property tmp_filename $upload_file]]
    
    #unzip theme into temporary directory
    catch { exec unzip -d $path $upload_tmpfiles  } errmsg
    set tmpthemedir [ file rootname $upload_files]

    #reading the manifest file
    if { [file exists $path/$tmpthemedir/skin.info] } {
    set file [open  $path/$tmpthemedir/skin.info]
    set xml_data [read $file]
    close $file
     set tree [xml_parse -persist $xml_data]
     set root_node [xml_doc_get_first_node $tree]
     set theme $root_node
     set theme_name [apm_required_attribute_value $theme name]
     set root_children [xml_node_get_children $root_node]
    foreach child $root_children {
       set child_name [xml_node_get_name $child]
       set properties($child_name) [apm_tag_value  $theme $child_name]
        }
    xml_doc_free $tree
    
    #moving the files in to the skins package
     set themepath "[acs_root_dir]/packages/skin"
     file mkdir $themepath/www/$theme_name
     set masterfiles $properties(masterfile)-master
     set source_masterfiles "$path/$tmpthemedir/$properties(masterfile)"
     set target_masterfiles "$themepath/master/$masterfiles"
     file rename -force $source_masterfiles.adp $target_masterfiles.adp
     file rename -force   $source_masterfiles.tcl $target_masterfiles.tcl
    
     foreach file   [ glob $path/$tmpthemedir/* ] {
 	  file copy -force $file  $themepath/www/$theme_name/
       }


    # Register the theme name with database
   
    db_dml insert_theme {}

    } else {
	ad_returnredirect "theme-error"
    }
    
  }   

