#!/bin/sh
# c8-lua-new: starts an app or a live tile of your own in Lua, and puts
# it on Start's lists so it can be run and pinned at once.
#
#   c8-lua-new app org.example.Notes "Notes"
#   c8-lua-new tile my-tile "My tile"
set -eu

usage() {
	cat >&2 <<END
Usage: c8-lua-new app ID "NAME"    an app: ID like org.example.Notes
       c8-lua-new tile ID "NAME"   a live tile: ID like my-tile

Makes a folder for it in ~/.local/share/c8-lua/ with a script to change,
and adds it to All apps (an app) or its Live tiles tab (a tile).
END
	exit 2
}

[ $# -eq 3 ] || usage
kind=$1 id=$2 name=$3
data=${XDG_DATA_HOME:-$HOME/.local/share}
dir=$data/c8-lua/$id

case $id in
''|.*|*[!A-Za-z0-9._-]*)
	echo "c8-lua-new: the id is letters, digits, dots, - and _" >&2
	exit 2
	;;
esac
case $name in
*'
'*)
	echo "c8-lua-new: the name is one line" >&2
	exit 2
	;;
esac
if [ -e "$dir" ]; then
	echo "c8-lua-new: $dir is already there" >&2
	exit 1
fi
# In a Lua string
quoted=$(printf '%s' "$name" | sed 's/[\\"]/\\&/g')

case $kind in
app)
	case $id in
	*.*) ;;
	*)
		echo "c8-lua-new: an app's id has a dot in it: org.example.Notes" >&2
		exit 2
		;;
	esac
	mkdir -p "$dir" "$data/applications"
	cat >"$dir/main.lua" <<END
-- $name. Try it:  c8-lua "$dir/main.lua"
-- What there is to build with: the c8-lua README, and the examples
-- beside it.
local c8 = require "c8"

local win

local function build()
	local hello = c8.label { text = "$quoted", style = "header" }
	return c8.column { spacing = 24, padding = { 40, 44, 40, 40 },
		hello,
		c8.button { label = "Press me", primary = true,
			on_click = function() hello:set("It works") end },
	}
end

c8.app {
	id = "$id",
	-- Every launch comes here; files are what it was opened with
	open = function(files)
		if not (win and win.open) then
			win = c8.window { title = "$quoted", build() }
		end
		win:present()
	end,
}
END
	cat >"$data/applications/$id.desktop" <<END
[Desktop Entry]
Type=Application
Name=$name
Exec=c8-lua "$dir/main.lua" %U
Icon=application-x-executable
Categories=Utility;
StartupWMClass=$id
END
	echo "Made $dir/main.lua"
	echo "It is in All apps as \"$name\"; or run: c8-lua \"$dir/main.lua\""
	;;
tile)
	mkdir -p "$dir" "$data/cont8nuum/widgets"
	cat >"$dir/tile.lua" <<END
-- $name: a live tile. The shell runs this for the tile and gives its id.
-- Fields are those of c8tile (template, heading, text1.., block, image,
-- color, badge, ...).
local c8 = require "c8"

c8.provider {
	tile = c8.args[1] or "$id",
	every = 60, -- seconds between updates
	update = function()
		return {
			template = "text",
			heading = "$quoted",
			text1 = os.date("%H:%M"),
		}
	end,
}
END
	cat >"$data/cont8nuum/widgets/$id.widget" <<END
[Widget]
Name=$name
Icon=application-x-executable
Category=Mine
Provider=c8-lua "$dir/tile.lua" %i
Size=medium
TryExec=c8-lua
END
	echo "Made $dir/tile.lua"
	echo "It is in All apps, Live tiles, as \"$name\": pin it from there."
	echo "After changing the script: c8tile restart $id"
	;;
*)
	usage
	;;
esac
