;Copyright (C) 2004-2009 John T. Haller of PortableApps.com

;Website: http://PortableApps.com/AudacityPortable

;This software is OSI Certified Open Source Software.
;OSI Certified is a certification mark of the Open Source Initiative.

;This program is free software; you can redistribute it and/or
;modify it under the terms of the GNU General Public License
;as published by the Free Software Foundation; either version 2
;of the License, or (at your option) any later version.

;This program is distributed in the hope that it will be useful,
;but WITHOUT ANY WARRANTY; without even the implied warranty of
;MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;GNU General Public License for more details.

;You should have received a copy of the GNU General Public License
;along with this program; if not, write to the Free Software
;Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

!define PORTABLEAPPNAME "Audacity Portable"
!define NAME "AudacityPortable"
!define APPNAME "Audacity"
!define VER "1.6.1.0"
!define WEBSITE "PortableApps.com/AudacityPortable"
!define DEFAULTEXE "audacity.exe"
!define DEFAULTAPPDIR "audacity"
!define DEFAULTSETTINGSPATH "settings"
!define LAUNCHERLANGUAGE "English"

;=== Program Details
Name "${PORTABLEAPPNAME}"
OutFile "..\..\${NAME}.exe"
Caption "${PORTABLEAPPNAME} | PortableApps.com"
VIProductVersion "${VER}"
VIAddVersionKey ProductName "${PORTABLEAPPNAME}"
VIAddVersionKey Comments "Allows ${APPNAME} to be run from a removable drive.  For additional details, visit ${WEBSITE}"
VIAddVersionKey CompanyName "PortableApps.com"
VIAddVersionKey LegalCopyright "John T. Haller"
VIAddVersionKey FileDescription "${PORTABLEAPPNAME}"
VIAddVersionKey FileVersion "${VER}"
VIAddVersionKey ProductVersion "${VER}"
VIAddVersionKey InternalName "${PORTABLEAPPNAME}"
VIAddVersionKey LegalTrademarks "PortableApps.com is a Trademark of Rare Ideas, LLC."
VIAddVersionKey OriginalFilename "${NAME}.exe"
;VIAddVersionKey PrivateBuild ""
;VIAddVersionKey SpecialBuild ""

;=== Runtime Switches
CRCCheck On
WindowIcon Off
SilentInstall Silent
AutoCloseWindow True
RequestExecutionLevel user
XPStyle On

; Best Compression
SetCompress Auto
SetCompressor /SOLID lzma
SetCompressorDictSize 32
SetDatablockOptimize On

;=== Include
;(Standard NSIS)
!include Registry.nsh
!include TextFunc.nsh
!insertmacro GetParameters

;(Custom)
!include ReadINIStrWithDefault.nsh

;=== Program Icon
Icon "..\..\App\AppInfo\appicon.ico"

;=== Languages
LoadLanguageFile "${NSISDIR}\Contrib\Language files\${LAUNCHERLANGUAGE}.nlf"
!include PortableApps.comLauncherLANG_${LAUNCHERLANGUAGE}.nsh

Var PROGRAMDIRECTORY
Var SETTINGSDIRECTORY
Var LAMEDIRECTORY
Var ADDITIONALPARAMETERS
Var EXECSTRING
Var PROGRAMEXECUTABLE
Var INIPATH
Var DISABLESPLASHSCREEN
Var ISDEFAULTDIRECTORY
Var APPTEMPDIRECTORY
Var TEMPDIREXISTS
Var FAILEDTORESTOREKEY
Var MISSINGFILEORPATH
Var APPLANGUAGE

Section "Main"
	;=== Find the INI file, if there is one
		IfFileExists "$EXEDIR\${NAME}.ini" "" NoINI
			StrCpy "$INIPATH" "$EXEDIR"
			Goto ReadINI

	ReadINI:
		;=== Read the parameters from the INI file
		${ReadINIStrWithDefault} $0 "$INIPATH\${NAME}.ini" "${NAME}" "${APPNAME}Directory" "App\${DEFAULTAPPDIR}"
		StrCpy "$PROGRAMDIRECTORY" "$EXEDIR\$0"
		${ReadINIStrWithDefault} $0 "$INIPATH\${NAME}.ini" "${NAME}" "SettingsDirectory" "Data\${DEFAULTSETTINGSPATH}"
		StrCpy "$SETTINGSDIRECTORY" "$EXEDIR\$0"
		${ReadINIStrWithDefault} $0 "$INIPATH\${NAME}.ini" "${NAME}" "LAMEDirectory" "App\LAME"
		StrCpy "$LAMEDIRECTORY" "$EXEDIR\$0"
		${ReadINIStrWithDefault} $ADDITIONALPARAMETERS "$INIPATH\${NAME}.ini" "${NAME}" "AdditionalParameters" ""
		${ReadINIStrWithDefault} $PROGRAMEXECUTABLE "$INIPATH\${NAME}.ini" "${NAME}" "${APPNAME}Executable"  "${DEFAULTEXE}"
		${ReadINIStrWithDefault} $DISABLESPLASHSCREEN "$INIPATH\${NAME}.ini" "${NAME}" "DisableSplashScreen" "false"
		Goto EndINI

	NoINI:
		;=== No INI file, so we'll use the defaults
		StrCpy "$ADDITIONALPARAMETERS" ""
		StrCpy "$PROGRAMEXECUTABLE" "${DEFAULTEXE}"
		StrCpy "$DISABLESPLASHSCREEN" "false"

		IfFileExists "$EXEDIR\App\${DEFAULTAPPDIR}\${DEFAULTEXE}" "" NoProgramEXE
			StrCpy "$PROGRAMDIRECTORY" "$EXEDIR\App\${DEFAULTAPPDIR}"
			StrCpy "$LAMEDIRECTORY" "$EXEDIR\App\LAME"
			StrCpy "$SETTINGSDIRECTORY" "$EXEDIR\Data\${DEFAULTSETTINGSPATH}"
			StrCpy "$ISDEFAULTDIRECTORY" "true"
	
	EndINI:
		IfFileExists "$PROGRAMDIRECTORY\$PROGRAMEXECUTABLE" FoundProgramEXE

	NoProgramEXE:
		;=== Program executable not where expected
		StrCpy $MISSINGFILEORPATH $PROGRAMEXECUTABLE
		MessageBox MB_OK|MB_ICONEXCLAMATION `$(LauncherFileNotFound)`
		Abort
		
	FoundProgramEXE:
		;=== Check if already running
		FindProcDLL::FindProc "$PROGRAMEXECUTABLE"                 
		StrCmp $R0 "1" "" CheckForSettings
			MessageBox MB_OK|MB_ICONEXCLAMATION `$(LauncherAlreadyRunning)`
			Abort
	
	CheckForSettings:
		IfFileExists "$SETTINGSDIRECTORY\*.*" SettingsFound
		;=== No settings found
		StrCmp $ISDEFAULTDIRECTORY "true" CopyDefaultSettings
		CreateDirectory $SETTINGSDIRECTORY
		Goto SettingsFound
	
	CopyDefaultSettings:
		CreateDirectory "$EXEDIR\Data"
		CreateDirectory "$EXEDIR\Data\settings"
		CopyFiles /SILENT $EXEDIR\App\DefaultData\settings\*.* $EXEDIR\Data\settings
		GoTo SettingsFound

	SettingsFound:
		;=== Figure out the temp registry store
		StrCpy "$APPTEMPDIRECTORY" "$TEMP\${NAME}\temp_files"
		CreateDirectory "$TEMP\${NAME}\temp_files"
		;SetOutPath $SETTINGSDIRECTORY

	;DisplaySplash:
		StrCmp $DISABLESPLASHSCREEN "true" GetPassedParameters
			;=== Show the splash screen before processing the files
			InitPluginsDir
			File /oname=$PLUGINSDIR\splash.jpg "${NAME}.jpg"	
			newadvsplash::show /NOUNLOAD 1200 0 0 -1 /L $PLUGINSDIR\splash.jpg

	GetPassedParameters:
		;=== Get any passed parameters
		${GetParameters} $0
		StrCmp "'$0'" "''" "" LaunchProgramParameters

		;=== No parameters
		StrCpy $EXECSTRING `"$PROGRAMDIRECTORY\$PROGRAMEXECUTABLE"`
		Goto AdditionalParameters

	LaunchProgramParameters:
		StrCpy $EXECSTRING `"$PROGRAMDIRECTORY\$PROGRAMEXECUTABLE" $0`

	AdditionalParameters:
		StrCmp $ADDITIONALPARAMETERS "" LaunchNow

		;=== Additional Parameters
		StrCpy $EXECSTRING `$EXECSTRING $ADDITIONALPARAMETERS`

	LaunchNow:
		${registry::MoveKey} "HKEY_CURRENT_USER\Software\Audacity" "HKEY_CURRENT_USER\Software\Audacity-BackupByAudacityPortable" $R0
		IfFileExists "$SETTINGSDIRECTORY\audacity_portable.reg" "" CreateOurKeys
		
	;RestoreTheKey:
		IfFileExists "$WINDIR\system32\reg.exe" "" RestoreTheKey9x
			nsExec::ExecToStack `"$WINDIR\system32\reg.exe" import "$SETTINGSDIRECTORY\audacity_portable.reg"`
			Pop $R0
			StrCmp $R0 '0' CreateOurKeys ;successfully restored key
	RestoreTheKey9x:
		${registry::RestoreKey} "$SETTINGSDIRECTORY\audacity_portable.reg" $R0
		StrCmp $R0 '0' CreateOurKeys ;successfully restored key
		StrCpy $FAILEDTORESTOREKEY "true"
		
	CreateOurKeys:
		${registry::Write} "HKEY_CURRENT_USER\Software\Audacity\Audacity\Directories" "TempDir" "$APPTEMPDIRECTORY" "REG_SZ" $0
		Sleep 100
		${registry::Write} "HKEY_CURRENT_USER\Software\Audacity\Audacity" "WantAssociateFiles" 0 "REG_DWORD" $0
		Sleep 100
		IfFileExists "$LAMEDIRECTORY\lame_enc.dll" "" NoLAMEEncoder
			${registry::Write} "HKEY_CURRENT_USER\Software\Audacity\Audacity\MP3" "MP3LibPath" "$LAMEDIRECTORY\lame_enc.dll" "REG_SZ" $0
			Goto GetAppLanguage
			
	NoLAMEEncoder:
		${registry::DeleteKey} "HKEY_CURRENT_USER\Software\Audacity\Audacity\MP3" $0

	GetAppLanguage:
		ReadEnvStr $APPLANGUAGE "PortableApps.comLocaleglibc"
		StrCmp $APPLANGUAGE "" StartProgramNow ;if not set, move on 
		StrCmp $APPLANGUAGE "en_US" 0 +2
			StrCpy $APPLANGUAGE "en"
		StrCmp $APPLANGUAGE "zh_CN" 0 GetCurrentLanguage
			StrCpy $APPLANGUAGE "zh"

	GetCurrentLanguage:
		ReadRegStr $0 HKCU "Software\Audacity\Audacity\Locale" "Language"
		StrCmp `"$APPLANGUAGE"` $0 StartProgramNow ;if the same, move on
		StrCmp $APPLANGUAGE "en" SetAppLanguage
		IfFileExists "$PROGRAMDIRECTORY\Languages\$APPLANGUAGE\*.*" SetAppLanguage StartProgramNow

	SetAppLanguage:
		WriteRegStr HKCU "Software\Audacity\Audacity\Locale" "Language" $APPLANGUAGE
		
	StartProgramNow:
		IfFileExists "$TEMP\audacity_1_2_temp\*.*" ExecTheApp
			StrCpy $TEMPDIREXISTS 'true'
		
	ExecTheApp:
		ExecWait $EXECSTRING
	
	;TheEnd:
		;=== Restore registry keys
	StrCmp $FAILEDTORESTOREKEY "true" SetOriginalKeyBack
		${registry::SaveKey} "HKEY_CURRENT_USER\Software\Audacity" "$SETTINGSDIRECTORY\audacity_portable.reg" "" $0
		Sleep 100
	SetOriginalKeyBack:
		${registry::DeleteKey} "HKEY_CURRENT_USER\Software\Audacity" $0
		Sleep 100
		${registry::MoveKey} "HKEY_CURRENT_USER\Software\Audacity-BackupByAudacityPortable" "HKEY_CURRENT_USER\Software\Audacity" $R0
	
	;EndWithoutRegRestore:
		StrCmp $DISABLESPLASHSCREEN "true" CleanupRunLocally
			Sleep 2000
			newadvsplash::stop /WAIT

	CleanupRunLocally:
		${registry::Unload}
		RMDir "$TEMP\${NAME}\temp_files\"
		IfFileExists "$TEMP\${NAME}\temp_files\*.*" "" RemoveTempDir
		MessageBox MB_YESNO|MB_ICONQUESTION `The ${PORTABLEAPPNAME} temp directory still has files within it.  If ${PORTABLEAPPNAME} had a problem and shut down unexpectedly, you may be able to recover your work from these files if you start it again.  If ${PORTABLEAPPNAME} closed normally, you may safely delete them.  Would you like to delete these files?` IDYES RemoveTempDir
		Goto EndOfLauncher
		
	RemoveTempDir:
		RMDir /r "$TEMP\${NAME}\"
	
	EndOfLauncher:
		${registry::Unload}
		newadvsplash::stop /WAIT
		StrCmp $TEMPDIREXISTS 'true' "" TheEnd
			RMDir '$TEMP\audacity_1_2_temp'
			
	TheEnd:
SectionEnd