Internet radio browser GUI for music/video streams from various directory services.

βŒˆβŒ‹ βŽ‡ branch:  streamtuner2


Check-in [17cd4bef20]

Overview
Comment:Combine path checks into main ForEach loop. Make-Shortcut() and Rewrite-Startscript() functions to embed those as $tasks too.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: 17cd4bef20504c37dffbe37a0693e5738e9a6726
User & Date: mario on 2016-11-20 23:31:58
Other Links: manifest | tags
Context
2016-11-22
00:59
A few more prettifications and fixes after testing; moved all checks into functions+$tasks. check-in: 8dd451d50d user: mario tags: trunk
2016-11-20
23:31
Combine path checks into main ForEach loop. Make-Shortcut() and Rewrite-Startscript() functions to embed those as $tasks too. check-in: 17cd4bef20 user: mario tags: trunk
16:43
More detailed Win installer scripts, as provided by Oliver. Plus *.ico file for packaging. check-in: 3670ccbb4b user: mario tags: trunk
Changes

Modified Makefile from [f4074f2854] to [8107f8766f].

44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68



69
70
71
72
73
74
75
	$(PACK) -t $@ $(OPTS) $(DEPS) -p "$(NAME)-VERSION.deb" st2.py
rpm:
	$(PACK) -t $@ $(OPTS) $(DEPS) -p "$(NAME)-VERSION.rpm" st2.py
tar:
	$(PACK) -t $@ $(OPTS) $(DEPS) -p "$(NAME)-VERSION.bin.txz" st2.py
exe:
	$(PACK) -t $@ $(OPTS) $(DEPS) -p "$(NAME)-VERSION.exe" \
	--exe-exec 'cmd /K c:\usr\share\streamtuner2\dev\install_python_gtk.bat' \
	--exe-dest c:/ --version $(VERSION) help/help.chm dev/install_python_gtk.* dev/*ico st2.py
arch:
	$(PACK) -t $@ $(OPTS) $(DEPS_A) -p "$(NAME)-VERSION.arch.txz" st2.py
pyz:
        #@BUG: relative package references leave a /tmp/doc/ folder
	$(PACK) -u packfile -s src -t zip --zip-shebang "/usr/bin/env python"	\
		-f -p "$(NAME)-$(VERSION).pyz" --prefix=./  .zip.py st2.py
src:
	cd .. && pax -wvJf streamtuner2/streamtuner2-$(VERSION).src.txz \
		streamtuner2/*.{py,png,desktop} streamtuner2/channels/*.{py,png} \
		streamtuner2/{bundle/,contrib/,help/,gtk3.xml.gz,NEWS,READ,PACK,PKG,CRED,Make,bin,.zip}*

# test .deb contents
check:
	dpkg-deb -c streamtuner2*deb
	dpkg-deb -I streamtuner2*deb
	rpm -qpil *rpm




# manual installation
install:
	mkdir	-p				$(DEST)/channels
	mkdir	-p				/usr/share/doc/streamtuner2/help/img
	install -m 755		bin		/usr/bin/streamtuner2
	$(INST)		*py		-t $(DEST)







|

















>
>
>







44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
	$(PACK) -t $@ $(OPTS) $(DEPS) -p "$(NAME)-VERSION.deb" st2.py
rpm:
	$(PACK) -t $@ $(OPTS) $(DEPS) -p "$(NAME)-VERSION.rpm" st2.py
tar:
	$(PACK) -t $@ $(OPTS) $(DEPS) -p "$(NAME)-VERSION.bin.txz" st2.py
exe:
	$(PACK) -t $@ $(OPTS) $(DEPS) -p "$(NAME)-VERSION.exe" \
	--exe-exec 'usr\share\streamtuner2\dev\install_python_gtk.bat' \
	--exe-dest c:/ --version $(VERSION) help/help.chm dev/install_python_gtk.* dev/*ico st2.py
arch:
	$(PACK) -t $@ $(OPTS) $(DEPS_A) -p "$(NAME)-VERSION.arch.txz" st2.py
pyz:
        #@BUG: relative package references leave a /tmp/doc/ folder
	$(PACK) -u packfile -s src -t zip --zip-shebang "/usr/bin/env python"	\
		-f -p "$(NAME)-$(VERSION).pyz" --prefix=./  .zip.py st2.py
src:
	cd .. && pax -wvJf streamtuner2/streamtuner2-$(VERSION).src.txz \
		streamtuner2/*.{py,png,desktop} streamtuner2/channels/*.{py,png} \
		streamtuner2/{bundle/,contrib/,help/,gtk3.xml.gz,NEWS,READ,PACK,PKG,CRED,Make,bin,.zip}*

# test .deb contents
check:
	dpkg-deb -c streamtuner2*deb
	dpkg-deb -I streamtuner2*deb
	rpm -qpil *rpm
	
upload:
	scp *.{deb,rpm,exe,pyz,arch,txz} io:st2/

# manual installation
install:
	mkdir	-p				$(DEST)/channels
	mkdir	-p				/usr/share/doc/streamtuner2/help/img
	install -m 755		bin		/usr/bin/streamtuner2
	$(INST)		*py		-t $(DEST)

Modified Packfile from [e7cc612b82] to [43249639b7].

9
10
11
12
13
14
15
16
17

18
19
20
21
22
	preprocess -D $(PKG_FLAG) -o $< $<

deb:	# complainy lintian needs a custom changelog.gz
	gzip -9c usr/share/doc/streamtuner2/NEWS > usr/share/doc/streamtuner2/changelog.gz
zip:
rpm:
exe:
	mv usr/share/streamtuner2/help/help.chm usr/share/doc/streamtuner2/help.chm
	mv usr/share/streamtuner2/dev/streamtuner2.ico usr/share/pixmaps/streamtuner2.ico

src:
tar:

arch:
	sed -i '1 s/python/python2/' usr/bin/streamtuner2







|

>





9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
	preprocess -D $(PKG_FLAG) -o $< $<

deb:	# complainy lintian needs a custom changelog.gz
	gzip -9c usr/share/doc/streamtuner2/NEWS > usr/share/doc/streamtuner2/changelog.gz
zip:
rpm:
exe:
	#mv usr/share/streamtuner2/help/help.chm usr/share/doc/streamtuner2/help.chm
	mv usr/share/streamtuner2/dev/streamtuner2.ico usr/share/pixmaps/streamtuner2.ico
	sed -i '10 s/"\/usr\/share\/streamtuner2"/os.path.realpath(os.path.dirname(__file__)+"\/..\/share\/streamtuner2")/' usr/bin/streamtuner2
src:
tar:

arch:
	sed -i '1 s/python/python2/' usr/bin/streamtuner2

Modified action.py from [c3fda330b1] to [ecd56b9293].

144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
        log.EXEC(cmd)
        os.system(cmd)
    except:
        log.ERR("Command not found:", cmd)

# Open help browser, chm, or streamtuner2 pages
def help(*args):
    for path in ("./help", "/usr/share/doc/streamtuner2/help", "./usr/share/doc/streamtuner2"):
        if not os.path.exists(path):
            continue
        if conf.windows:
            return run(("%s/help.chm" % path).replace("/", '\\'))
        else:
            return run("yelp %s" % path)
    return browser("http://fossil.include-once.org/streamtuner2/doc/tip/help/html/index.html")







|







144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
        log.EXEC(cmd)
        os.system(cmd)
    except:
        log.ERR("Command not found:", cmd)

# Open help browser, chm, or streamtuner2 pages
def help(*args):
    for path in ("./help", "/usr/share/doc/streamtuner2/help", "../share/streamtuner2/help"):
        if not os.path.exists(path):
            continue
        if conf.windows:
            return run(("%s/help.chm" % path).replace("/", '\\'))
        else:
            return run("yelp %s" % path)
    return browser("http://fossil.include-once.org/streamtuner2/doc/tip/help/html/index.html")

Modified bin from [26fdffbcd8] to [e021ede091].

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/env python
# api: cli
# type: wrapper
# title: streamtuner2
# pack: bin=/usr/bin/streamtuner2
#
# Invocation script for /usr/share/streamtuner2/st2.py

import sys
sys.path.insert(0, "/usr/share/streamtuner2")

import st2
st2.main()








|




1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/env python
# api: cli
# type: wrapper
# title: streamtuner2
# pack: bin=/usr/bin/streamtuner2
#
# Invocation script for /usr/share/streamtuner2/st2.py

import sys, os
sys.path.insert(0, "/usr/share/streamtuner2")

import st2
st2.main()

Modified dev/install_python_gtk.ps1 from [dc4eb173bc] to [8870991e14].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<#
 #
 # Run as post-install script for .exe package
 #
 #  - downloads Python + Gtk
 #  - some python libraries
 #  - and runs their respective installers
 #  - crafts streamtuner2 desktop shortcut
 #  - crafts streamtuner2 shortcuts in Start menu
 #
 #>

[CmdletBinding()]            
Param(            
)            

# admin check            
function Test-IsElevated {
    [CmdletBinding()]
    param(
    )
    [Security.Principal.WindowsPrincipal] $Identity = [Security.Principal.WindowsIdentity]::GetCurrent()
    $Identity.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}


# prerequisites check
function Check-Prerequisites {
    [CmdletBinding()]
    param(
    )

    ForEach ($task in $tasks) {
       $title, $url, $cmd, $args, $regkey, $reghive = $task;
        if ($regkey) { 
            if (!(Get-Item -Path ($regHive + "\" + $regkey))) {     # avoid runtime error if not existent (not working in PS1)
                Write-Host $title " not found"
                return 0
            }
            else {
                Write-Host (Get-ItemProperty -Path ($regHive + "\" + $regkey) -Name "DisplayName".DisplayName).DisplayName " found"
            }
        }
        elseif ($title = "Python requests") {
            if (!(Get-Item -Path "$PYTHON\Lib\site-packages\requests-2.12.1-py2.7.egg")) {
                write-Host $title " not found"
                return 0
            }













|
<




|
<








|
|
<

|

|




|







1
2
3
4
5
6
7
8
9
10
11
12
13
14

15
16
17
18
19

20
21
22
23
24
25
26
27
28
29

30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<#
 #
 # Run as post-install script for .exe package
 #
 #  - downloads Python + Gtk
 #  - some python libraries
 #  - and runs their respective installers
 #  - crafts streamtuner2 desktop shortcut
 #  - crafts streamtuner2 shortcuts in Start menu
 #
 #>

[CmdletBinding()]            
Param()            


# admin check            
function Test-IsElevated {
    [CmdletBinding()]
    param()

    [Security.Principal.WindowsPrincipal] $Identity = [Security.Principal.WindowsIdentity]::GetCurrent()
    $Identity.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}


# prerequisites check
function Check-Prerequisites {
    [CmdletBinding()]
    param()


    ForEach ($task in $tasks) {
       $title, $url, $cmd, $args, $regkey, $check = $task;
        if ($regkey) { 
            if (!(Get-Item -Path $regkey)) {     # avoid runtime error if not existent (not working in PS1)
                Write-Host $title " not found"
                return 0
            }
            else {
                Write-Host (Get-ItemProperty -Path $regkey -Name "DisplayName".DisplayName).DisplayName " found"
            }
        }
        elseif ($title = "Python requests") {
            if (!(Get-Item -Path "$PYTHON\Lib\site-packages\requests-2.12.1-py2.7.egg")) {
                write-Host $title " not found"
                return 0
            }
64
65
66
67
68
69
70

71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146



































147
148
149




































150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174

175
176
177
178
179
180
181
182
183
184
185
186


187


188
189

190
191
192
193
194
195
196
197
198












199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
    return 1
}

# default paths
$TEMP = $env:TEMP
$PYTHON = "C:\Python27"
$OutputEncoding = [System.Text.Encoding]::UTF8


#-- Get ST installation folder
$ScriptPath = (Split-Path $MyInvocation.MyCommand.Path -Parent).Split("\") #PS1/2 compatibility"

$UsrFolder=$ScriptPath[0]+"\"
for ($i=1; $i -le $ScriptPath.Length - 4; $i++) {
    $UsrFolder = $UsrFolder+$ScriptPath[$i]+"\"
}

if (!(Test-Path -Path("..\..\..\bin\streamtuner2"))) {
    Write-Host -foregroundcolor Red "The Streamtuner2 start script could not be found. The installation cannot continue."
    Write-Host -foregroundcolor Red "Please do not change the folder structure of the Streamtuner2 package!"
    Write-Host -foregroundcolor Red "Press any key to exit ..."
    $null = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    exit;
}    


# prepare registry lookup
$regPathCU = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall"
$regPath = "HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
if(!(Test-Path $regPath)) {
    $regPath = "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall"
}


#-- what and how to install
#   each row is a list of (title,url,cmd,msi args,regkey,reghive)
$tasks = @(
  @(
    "Python 2.7.12",                                                  # title
    "https://www.python.org/ftp/python/2.7.12/python-2.7.12.msi",     # url
    "",                                                               # custom cmd
    "TARGETDIR=C:\Python27 /qb",                                      # msi args
    "{9DA28CE5-0AA5-429E-86D8-686ED898C665}",                         # registry
    "$regPath"                                                        # registry hive/path
  ),
  @(
    "PyGtk 2.24.2",
    "http://ftp.gnome.org/pub/GNOME/binaries/win32/pygtk/2.24/pygtk-all-in-one-2.24.2.win32-py2.7.msi",
    "",
    "TARGETDIR=C:\Python27 ADDLOCAL=ALL REMOVE=PythonExtensionModulePyGtkSourceview2,PythonExtensionModulePyGoocanvas,PythonExtensionModulePyRsvg,DevelopmentTools /qb",
    "{09F82967-D26B-48AC-830E-33191EC177C8}",
    "$regPath"                                                               
  ),
  @(
    "Python requests",
    "requests", # no download url, pip handles this
    "easy_install",
    "",
    "",
    ""
  ),
  @(
    "LXML 2.3",
    "https://pypi.python.org/packages/3d/ee/affbc53073a951541b82a0ba2a70de266580c00f94dd768a60f125b04fca/lxml-2.3.win32-py2.7.exe",
    "",
    "",
    "lxml-py2.7",
    "$regPathCU"
  ),
  @(
    "PyQuery 1.2.1",
    "https://pypi.python.org/packages/62/71/8ac1f5c0251e51714d20e4b102710d5eee1683c916616129552b0a025ba5/pyquery-1.2.17-py2.py3-none-any.whl",
    "pip",
    "",
    "",
    ""
  ),
  @(
    "PIL 1.1.7",
    "http://effbot.org/downloads/PIL-1.1.7.win32-py2.7.exe",
    "",
    "",
    "PIL-py2.7",
    "$regPathCU"



































  )
)








































#-- ask before running
Write-Host ""
Write-Host -foregroundcolor Yellow "Do you want to install Python 2.7 and Gtk dependencies now?"
Write-Host -foregroundcolor Yellow "–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––"
Write-Host -foregroundcolor Yellow " β†’ This will install 32-bit versions of Python and Gtk."
Write-Host -foregroundcolor Yellow " β†’ Downloads will remain in $TEMP"
if(!(Test-IsElevated)) {
    Write-Host ""
    Write-Host -foregroundcolor red "┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓"
    Write-Host -foregroundcolor red "┃ ⚠ β›”  If you run this script in non-elevated mode you will not be able to  ┃"
    Write-Host -foregroundcolor red "┃      uninstall Python and Gtk using the control panelsΒ΄ software list.    ┃"
    Write-Host -foregroundcolor red "┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛"
}
Write-Host ""
$y = Read-Host "y/n"
if ($y -notmatch "y|Y|1") {
    exit;
}
Write-Host ""


#-- check prereqs installation

Write-Host ""
Write-Host "Checking installation"
Write-Host "------------------------"
Write-Host ""


$prereqs = (Check-Prerequisites)
if ($prereqs -match 1) {
    Write-Host ""
    Write-Host -foregroundcolor Yellow "All required Python components are already installed."
    Write-Host -foregroundcolor Yellow "Do you want to (R)einstall them or (S)kip the installation?"
    $y = Read-Host "R/S"


}


if ($y -notmatch "s|S|2" -OR $prereqs -match 0) {
    #-- process

    ForEach ($task in $tasks) {
        $title, $url, $cmd, $args, $regkey, $regpath = $task;

        Write-Host ""
        Write-Host "Installing $title"
        Write-Host "------------------------"
        Write-Host ""
        chdir($TEMP);














        # get "filename" part from url
        $file = [regex]::match($url, "/([^/]+?)([\?\#]|$)").Groups[1].Value;

        # download
        if ($url -match "https?://.+") {
            Write-Host -foregroundcolor DarkGreen  " β†’ download( $url )"
            $wget = New-Object System.Net.WebClient
            $wget.DownloadFile($url, "$TEMP\$file");
        }

        # run shorthand or custom command
        if ($cmd) {
            chdir($PYTHON)
            if ($cmd -eq "pip") {
                $cmd = "$PYTHON\Scripts\pip.exe install $TEMP\$file"
            }
            elseif ($cmd -match "^(easy|easy_install|silent)$") {
                 $cmd = "$PYTHON\Scripts\easy_install.exe $url"
            }
            Write-Host -foregroundcolor DarkYellow   " β†’ exec( $cmd )"
            Invoke-Expression "& $cmd"
        }
        # msi
        elseif ($file -match ".+.msi$") {
            write-host -foregroundcolor DarkYellow " β†’ exec( msiexec /i $file $args )"
            Start-Process -Wait msiexec -ArgumentList /i,"$TEMP\$file",$args
            if ($regkey) { Try {
                Set-ItemProperty -Path "$regPath\$regkey" -Name "WindowsInstaller"  -Value "0"
            } Catch {} }
        }
        # exe
        elseif ($file -match ".+.exe$") {
            write-host -foregroundcolor DarkYellow " β†’ exec( $file $args )"
            if ($args) {
                Start-Process -Wait "$TEMP\$file" -ArgumentList $args
            }
            else {
                Start-Process -Wait "$TEMP\$file"
            }
        }
        # other files
        else {
          echo " β†’ exec( $file )"
          & "$TEMP\$file"
        }
    }
}


#-- modify ST2 wrapper script
Write-Host ""
Write-Host "Configuring Streamtuner2 ..."
$WrapperScript = Get-Content -Path $UsrFolder"\bin\streamtuner2"
for ($i=0; $i -lt $WrapperScript.Length ; $i++) {
    $WrapperScript[$i] = $WrapperScript[$i].Replace("sys.path.insert(0, " + """" + "/usr/","sys.path.insert(0, " + """" + $UsrFolder)
    Out-File -FilePath $UsrFolder"\bin\streamtuner2.new" -Encoding ascii -Append -InputObject $WrapperScript[$i]
}

if (Test-Path -Path $UsrFolder"\bin\streamtuner2.bak") {
    Remove-Item -Path $UsrFolder"\bin\streamtuner2.bak" -Force
}
Rename-Item -NewName "streamtuner2.bak" -Path $UsrFolder"\bin\streamtuner2" #save old script
Rename-Item -NewName "streamtuner2" -Path $UsrFolder"\bin\streamtuner2.new"
Set-Acl $UsrFolder"\bin\streamtuner2" (Get-Acl $UsrFolder"\bin\streamtuner2.bak") # set file permissions 


Write-Host ""
Write-Host "Creating Shortcuts ..."
#-- create ST2.lnk on desktop
$WshShell = New-Object -ComObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\Streamtuner2.lnk")
$Shortcut.TargetPath = "$PYTHON\pythonw.exe"
$Shortcut.Arguments = $UsrFolder + "bin\streamtuner2"
$Shortcut.IconLocation = $UsrFolder + "share\pixmaps\streamtuner2.ico"
$Shortcut.WorkingDirectory = $UsrFolder + "bin"
$Shortcut.Save()

#-- create ST2 links in start menu
$StartMenuFolder = "$env:USERPROFILE\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Streamtuner2"
if (!(Test-Path -Path $StartMenuFolder)) {
    New-Item -Path $StartMenuFolder -ItemType directory
}
$WshShell = New-Object -ComObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$StartMenuFolder\Streamtuner2.lnk")
$Shortcut.TargetPath = "$PYTHON\pythonw.exe"
$Shortcut.Arguments = $UsrFolder + "bin\streamtuner2"
$Shortcut.IconLocation = $UsrFolder + "share\pixmaps\streamtuner2.ico"
$Shortcut.WorkingDirectory = $UsrFolder + "bin"
$Shortcut.Save()

$Shortcut = $WshShell.CreateShortcut("$StartMenuFolder\Help.lnk")
$Shortcut.TargetPath = $UsrFolder + "share\doc\streamtuner2\help.chm"
$Shortcut.Save()

Write-Host ""
Write-Host -ForegroundColor Yellow "Installation completed."







>



<




<








<


|
|
|











|
|






|
|







|






|
|







|






|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>



>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

















|
<






>




<
<






>
>
|
>
>
|
|
>
|
|

|
|
|
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>

|
|

|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
61
62
63
64
65
66
67
68
69
70
71

72
73
74
75

76
77
78
79
80
81
82
83

84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233

234
235
236
237
238
239
240
241
242
243
244


245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
















































    return 1
}

# default paths
$TEMP = $env:TEMP
$PYTHON = "C:\Python27"
$OutputEncoding = [System.Text.Encoding]::UTF8
$StartMenu = "$env:USERPROFILE\AppData\Roaming\Microsoft\Windows\Start Menu\Programs"

#-- Get ST installation folder
$ScriptPath = (Split-Path $MyInvocation.MyCommand.Path -Parent).Split("\") #PS1/2 compatibility"

$UsrFolder=$ScriptPath[0]+"\"
for ($i=1; $i -le $ScriptPath.Length - 4; $i++) {
    $UsrFolder = $UsrFolder+$ScriptPath[$i]+"\"
}

if (!(Test-Path -Path("..\..\..\bin\streamtuner2"))) {
    Write-Host -foregroundcolor Red "The Streamtuner2 start script could not be found. The installation cannot continue."
    Write-Host -foregroundcolor Red "Please do not change the folder structure of the Streamtuner2 package!"
    Write-Host -foregroundcolor Red "Press any key to exit ..."
    $null = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    exit;
}    


# prepare registry lookup
$regPathCU = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall"
$regPathHK = "HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
if(!(Test-Path $regPathHK)) {
    $regPathHK = "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall"
}


#-- what and how to install
#   each row is a list of (title,url,cmd,msi args,regkey,reghive)
$tasks = @(
  @(
    "Python 2.7.12",                                                  # title
    "https://www.python.org/ftp/python/2.7.12/python-2.7.12.msi",     # url
    "",                                                               # custom cmd
    "TARGETDIR=C:\Python27 /qb",                                      # msi args
    "$regPathHK\{9DA28CE5-0AA5-429E-86D8-686ED898C665}",              # registry
    "$regPathHK\{9DA28CE5-0AA5-429E-86D8-686ED898C665}"               # installed check
  ),
  @(
    "PyGtk 2.24.2",
    "http://ftp.gnome.org/pub/GNOME/binaries/win32/pygtk/2.24/pygtk-all-in-one-2.24.2.win32-py2.7.msi",
    "",
    "TARGETDIR=C:\Python27 ADDLOCAL=ALL REMOVE=PythonExtensionModulePyGtkSourceview2,PythonExtensionModulePyGoocanvas,PythonExtensionModulePyRsvg,DevelopmentTools /qb",
    "$regPathHK\{09F82967-D26B-48AC-830E-33191EC177C8}",
    "$regPathHK\{09F82967-D26B-48AC-830E-33191EC177C8}"
  ),
  @(
    "Python requests",
    "requests", # no download url, pip handles this
    "easy_install",
    "",
    "",
    "$PYTHON\Lib\site-packages\requests-2.12.1-py2.7.egg"
  ),
  @(
    "LXML 2.3",
    "https://pypi.python.org/packages/3d/ee/affbc53073a951541b82a0ba2a70de266580c00f94dd768a60f125b04fca/lxml-2.3.win32-py2.7.exe",
    "",
    "",
    "$regPathCU\lxml-py2.7",
    "$regPathCU\lxml-py2.7"
  ),
  @(
    "PyQuery 1.2.1",
    "https://pypi.python.org/packages/62/71/8ac1f5c0251e51714d20e4b102710d5eee1683c916616129552b0a025ba5/pyquery-1.2.17-py2.py3-none-any.whl",
    "pip",
    "",
    "",
    "$PYTHON\Lib\site-packages\pyquery-1.2.17.dist-info"
  ),
  @(
    "PIL 1.1.7",
    "http://effbot.org/downloads/PIL-1.1.7.win32-py2.7.exe",
    "",
    "",
    "$regPathCU\PIL-py2.7",
    "$regPathCU\PIL-py2.7"
  ),
  @(
    "ST2 invocation (relocatability)",
    "",
    'Rewrite-Startscript',
    "",
    "",
    "$UsrFolder\bin\streamtuner2.bak"
  ),
  @(
    "Desktop shortcut",
    "",
    'Make-Shortcut -dir $Home\Desktop -name Streamtuner2.lnk -target $PYTHON\pythonw.exe -arg $UsrFolder\bin\streamtuner2',
    "",
    "",
    "$Home\Desktop\Streamtuner2.lnk"
  ),
  @(
    "Startmenu shortcut",
    "",
    'Make-Shortcut -dir "$StartMenu\Streamtuner2" -name Streamtuner2.lnk -target $PYTHON\pythonw.exe -arg $UsrFolder\bin\streamtuner2',
    "",
    "",
    ""
  ),
  @(
    "Startmenu help.chm",
    "",
    'Make-Shortcut -dir "$StartMenu\Streamtuner2" -name Help.lnk -target $UsrFolder\share\streamtuner2\help\help.chm -arg $false',
    "",
    "",
    ""
  ),
  @(
    "**FINISHED**.", "", '$true', "", "", ""
  )
)

#-- create Desktop/Startmenu shortcuts
function Make-Shortcut {
    [CmdletBinding()]
    param($dir, $name, $target, $arg)
    if (!(Test-Path -Path $dir)) {
        New-Item -Path $dir -ItemType directory
    }
    $wsh = New-Object -ComObject WScript.Shell
    $lnk = $wsh.CreateShortcut("$dir\$name")
    $lnk.TargetPath = $target
    if ($arg) {
        $lnk.Arguments = $arg
        $lnk.IconLocation = $UsrFolder + "share\pixmaps\streamtuner2.ico"
        $lnk.WorkingDirectory = $UsrFolder + "bin"
    }
    $lnk.Save()
}


#-- modify ST2 wrapper script
function Rewrite-Startscript {
    [CmdletBinding()]
    param()
    $WrapperScript = Get-Content -Path $UsrFolder"\bin\streamtuner2"
    for ($i=0; $i -lt $WrapperScript.Length ; $i++) {
        $WrapperScript[$i] = $WrapperScript[$i].Replace("sys.path.insert(0, " + """" + "/usr/","sys.path.insert(0, " + """" + $UsrFolder)
        Out-File -FilePath $UsrFolder"\bin\streamtuner2.new" -Encoding ascii -Append -InputObject $WrapperScript[$i]
    }

    if (Test-Path -Path $UsrFolder"\bin\streamtuner2.bak") {
        Remove-Item -Path $UsrFolder"\bin\streamtuner2.bak" -Force
    }
    Rename-Item -NewName "streamtuner2.bak" -Path $UsrFolder"\bin\streamtuner2" #save old script
    Rename-Item -NewName "streamtuner2" -Path $UsrFolder"\bin\streamtuner2.new"
    Set-Acl $UsrFolder"\bin\streamtuner2" (Get-Acl $UsrFolder"\bin\streamtuner2.bak") # set file permissions 
}



#-- ask before running
Write-Host ""
Write-Host -foregroundcolor Yellow "Do you want to install Python 2.7 and Gtk dependencies now?"
Write-Host -foregroundcolor Yellow "–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––"
Write-Host -foregroundcolor Yellow " β†’ This will install 32-bit versions of Python and Gtk."
Write-Host -foregroundcolor Yellow " β†’ Downloads will remain in $TEMP"
if(!(Test-IsElevated)) {
    Write-Host ""
    Write-Host -foregroundcolor red "┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓"
    Write-Host -foregroundcolor red "┃ ⚠ β›”  If you run this script in non-elevated mode you will not be able to  ┃"
    Write-Host -foregroundcolor red "┃      uninstall Python and Gtk using the control panelsΒ΄ software list.    ┃"
    Write-Host -foregroundcolor red "┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛"
}
Write-Host ""
if ((Read-Host "y/n") -notmatch "[yY123ar]") {

    exit;
}
Write-Host ""


#-- check prereqs installation
<#
Write-Host ""
Write-Host "Checking installation"
Write-Host "------------------------"
Write-Host ""


$prereqs = (Check-Prerequisites)
if ($prereqs -match 1) {
    Write-Host ""
    Write-Host -foregroundcolor Yellow "All required Python components are already installed."
    Write-Host -foregroundcolor Yellow "Do you want to (R)einstall them or (S)kip the installation?"
    $y = Read-Host "R/S"
    if ($y -match "s|S|2") {
        exit
    }
}
#>

#-- process
$reinstall = "ask"
ForEach ($task in $tasks) {
    $title, $url, $cmd, $args, $regkey, $testpath = $task;

    Write-Host ""
    Write-Host "Installing $title"
    Write-Host "------------------------"
    Write-Host ""
    chdir($TEMP);
    
    # test if element (directory/file or registry key) already exists:
    if ($reinstall -eq "all") {
    }
    elseif ($testpath -AND (Test-Path -Path $testpath)) {
        echo " β†’ Is already present."
        if ($reinstall -eq "none") { continue }
        $y = Read-Host "   Reinstall [y/N/all/none]?"
        if ($y -match "all|always|re|A") { $reinstall = "all" }
        elseif ($y -match "never|none|skipall|S") { $reinstall = "none"; continue }
        elseif ($y -match "y|yes|1|go|R") { } # YES
        else { continue } # everything else counts as NO
    }

    # get "filename" part from url
    $file = [regex]::match($url, "/([^/]+?)([\?\#]|$)").Groups[1].Value;

    # download
    if ($url -match "https?://.+") {
        Write-Host -foregroundcolor DarkGreen  " β†’ download( $url )"
        $wget = New-Object System.Net.WebClient
        $wget.DownloadFile($url, "$TEMP\$file");
    }

    # run shorthand or custom command
    if ($cmd) {
        chdir($PYTHON)
        if ($cmd -eq "pip") {
            $cmd = "$PYTHON\Scripts\pip.exe install $TEMP\$file"
        }
        elseif ($cmd -match "^(easy|easy_install|silent)$") {
             $cmd = "$PYTHON\Scripts\easy_install.exe $url"
        }
        Write-Host -foregroundcolor DarkYellow   " β†’ exec( $cmd )"
        Invoke-Expression "$cmd"
    }
    # msi
    elseif ($file -match ".+.msi$") {
        write-host -foregroundcolor DarkYellow " β†’ exec( msiexec /i $file $args )"
        Start-Process -Wait msiexec -ArgumentList /i,"$TEMP\$file",$args
        if ($regkey) { Try {
            Set-ItemProperty -Path "$regkey" -Name "WindowsInstaller"  -Value "0"
        } Catch {} }
    }
    # exe
    elseif ($file -match ".+.exe$") {
        write-host -foregroundcolor DarkYellow " β†’ exec( $file $args )"
        if ($args) {
            Start-Process -Wait "$TEMP\$file" -ArgumentList $args
        }
        else {
            Start-Process -Wait "$TEMP\$file"
        }
    }
    # other files
    elseif ($file) {
      echo " β†’ exec( $file )"
      & "$TEMP\$file"
    }
}