#!/usr/bin/tclsh

###############################################################
# SecPanel helper
# Converting from old profile seetings to new version (0.5)
###############################################################

proc cp {} {
    global env

    if {! [file exists "$env(HOME)/.secpanel/sites"]} {
	puts "No sites-file to convert"
	return
    }

    set sf [open "$env(HOME)/.secpanel/sites"]

    while {[gets $sf line] >= 0} {
	set nf [open "$env(HOME)/.secpanel/profiles/newfiles.tmp" w]

	set sitetitle [lindex [split $line \#] 0]
	set sitehost [lindex [split $line \#] 1]
	set siteuser [lindex [split $line \#] 2]

	set defs [open "$env(HOME)/.secpanel/default.profile"]
	while {[gets $defs defline] >= 0} {
	    switch -regexp $defline {
		"^set title .*" {
		    regsub -all " " $sitetitle "" filetitle
		    puts $nf "set title \"$sitetitle\""
		}
		"^set host .*" {
		    puts $nf "set host \"$sitehost\""
		}
		"^set user .*" {
		    puts $nf "set user \"$siteuser\""
		}
		default {
		    puts $nf $defline
		}
	    }
	}
	close $defs
	close $nf
	file copy -force "$env(HOME)/.secpanel/profiles/newfiles.tmp" "$env(HOME)/.secpanel/profiles/$filetitle.profile"
	unset filetitle
	file delete -force "$env(HOME)/.secpanel/profiles/newfiles.tmp"
    }
    close $sf
}

proc do_backup {} {
    global env
    set butime [clock seconds]
    file copy -force "$env(HOME)/.secpanel" "$env(HOME)/secpanel_backup$butime"
    puts "Put Backup of $env(HOME)/.secpanel to $env(HOME)/secpanel_backup$butime"
}

proc moveprofs {} {
    global env
    file delete -force "$env(HOME)/.secpanel/default.profile"
    foreach file [glob -nocomplain "$env(HOME)/.secpanel/*.profile"] {
	file copy -force "$file" "$env(HOME)/.secpanel/profiles"
	file delete -force "$file"
    }
    file delete -force "$env(HOME)/.secpanel/sites"
}

puts "Doing profile conversion..."
do_backup
file mkdir "$env(HOME)/.secpanel/profiles"
cp
moveprofs
