; Tucan Studio Installer script.
;
; Drop the install drawer (this script lives next to the `app` binary
; + icons/ + images/ + syntax/) onto any Workbench-targeted
; volume, double-click "Install", and the Installer command will:
;
;   1. Ask the user where to put Tucan Studio (default: SYS:).
;   2. Copy the IDE binary (installed as "TucanStudio") + the images/ +
;      syntax/ dirs into a chosen drawer under that location.
;   3. Ask which icon style to use and install it as TucanStudio.info.
;   4. Create the S:tucanExtensions
;      drawer (one boot file per installed extension lives there).
;   5. Patch S:User-Startup with a Tucan Studio block that:
;        - Wires the `tucan:` assign at every boot.
;        - Loops every file in S:tucanExtensions/ and Executes it
;          so an extension's onInstall lines apply across reboots.
;
; The block is bracketed by ;BEGIN Tucan Studio / ;END Tucan Studio so a
; subsequent install replaces it cleanly via the standard
; (startup) function instead of stacking duplicate entries.
;
; Tested against both Commodore Installer 43.x (AmigaOS) and the
; MorphOS Installer compatibility layer.

(welcome "Tucan Studio installer\n\n"
         "Installs Tucan Studio, a cross-platform IDE for AmigaOS (68k), MorphOS (ppc), MacOS (arm64) and Linux (x64, arm64, ppc32, ppc64)\n\n")

; --- Destination ---------------------------------------------------
;
; We install everything under <chosen-dir>/TucanStudio/, defaulting to
; SYS:. The user can override the drawer name too.

(set #dest-parent
    (askdir
        (prompt "Where do you want to install Tucan Studio?\n\n"
                "A new \"TucanStudio\" drawer will be created here.")
        (help "Pick the parent volume or directory.")
        (default "SYS:")
        (newpath)
    )
)

(set #dest-name
    (askstring
        (prompt "Name of the Tucan Studio drawer:")
        (help "The directory name created under " #dest-parent
              ". You'll see this drawer in Workbench.")
        (default "TucanStudio")
    )
)

(set #dest (tackon #dest-parent #dest-name))

; --- Create the drawer + copy payload ------------------------------

; No (infos) here — Workbench's default drawer icon is dull. We install
; our own custom Tucan drawer icon just below instead.
(makedir #dest
    (prompt "Creating " #dest)
    (help "Tucan Studio's files will be copied into this drawer.")
    (confirm)
)

; The IDE binary ships as "TucanStudio" next to this Install script in
; the staged drawer. NO (infos) here — the icon is chosen + installed
; separately below so the user can pick a style.
(copyfiles
    (prompt "Copying Tucan Studio program...")
    (help "Copies the IDE executable to " #dest ".")
    (source "TucanStudio")
    (dest #dest)
)

; --- Program icon --------------------------------------------------
;
; Four prebuilt icons ship in the icons/ drawer. Let the user pick the
; one that suits their Workbench (colour depth + icon.library version),
; then install it as the program's icon, TucanStudio.info. All four are
; WBTOOL icons with a 100000-byte stack.
(set #icon-style
    (askchoice
        (prompt "Which program icon would you like?")
        (help "8-colour works on ANY Workbench (1.3+).\n"
              "256-colour GlowIcon needs OS3.5+ (it falls back to the "
              "8-colour image on plain 3.1).\n"
              "NewIcons needs the NewIcons commodity running, or OS3.5+.\n"
              "True-colour PNG is a MorphOS / OS4 format and won't show "
              "on stock AmigaOS.\n\n"
              "If unsure, keep the default 256-colour GlowIcon.")
        (choices "8-colour (any Workbench)"
                 "256-colour GlowIcon (OS3.5+)"
                 "NewIcons (needs NewIcons/OS3.5)"
                 "True-colour PNG (MorphOS/OS4)")
        (default 1)
    )
)

(set #icon-file
    (select #icon-style
        "icons/8-Colour.info"
        "icons/256-Colour.info"
        "icons/NewIcons.info"
        "icons/TrueColour.info"
    )
)

; Matching DRAWER icon in the SAME style, so a NewIcons program pick
; also gets a NewIcons drawer (etc). Same four-way order as #icon-style.
(set #drawer-file
    (select #icon-style
        "icons/Drawer-8-Colour.info"
        "icons/Drawer-256-Colour.info"
        "icons/Drawer-NewIcons.info"
        "icons/Drawer-TrueColour.info"
    )
)

(copyfiles
    (prompt "Installing the program icon...")
    (help "Copies your chosen icon to " #dest " as TucanStudio.info.")
    (source #icon-file)
    (dest #dest)
    (newname "TucanStudio.info")
)

; A drawer's Workbench icon lives in a sibling "<name>.info" file in the
; PARENT directory (not inside the drawer). Copy the chosen-style WBDRAWER
; icon beside the new drawer as "<dest-name>.info" so the created drawer
; shows the Tucan icon (open-drawer art while selected) in that same style.
(copyfiles
    (prompt "Installing the drawer icon...")
    (help "Copies the Tucan drawer icon to " #dest ".info in your chosen style.")
    (source #drawer-file)
    (dest #dest-parent)
    (newname (cat #dest-name ".info"))
)

; images/ — icons.png + tucan-studio.png splash. Must sit next to the
; binary because Program.aml resolves them as "images/..." relative
; paths at runtime.
(copyfiles
    (prompt "Copying images (icons, splash)...")
    (help "Copies the images/ directory to " #dest "/images.")
    (source "images")
    (dest (tackon #dest "images"))
    (all)
)

; syntax/ — per-language behaviour JSON files. LanguageBehaviour
; resolves them as "syntax/<lang>.behaviour.json" relative to the
; binary's CWD.
(copyfiles
    (prompt "Copying syntax definitions...")
    (help "Copies the syntax/ directory to " #dest "/syntax.")
    (source "syntax")
    (dest (tackon #dest "syntax"))
    (all)
)

; extensions/ — an EMPTY drawer. The package bundles no extensions any
; more: the Extension Manager runs remote-only (config/extensions.json
; sets useLocalCatalog=false) and installs what it needs from the
; registry at tucan.amlang.net, am-git included. We still create the
; drawer so the first install has somewhere to land without prompting.
(makedir (tackon #dest "extensions")
    (prompt "Creating extensions drawer...")
    (help "Extensions you install from Manage Extensions are stored in "
          #dest "/extensions.")
)

; config/ — Tucan Studio's OWN settings (fonts.json, settings.json,
; workspaces.json, repos.json). Read at startup relative to the binary's
; CWD. On a FRESH install we copy the shipped defaults; on an UPGRADE (a
; config/ already exists) we ask first, defaulting to NO, so a reinstall
; never silently wipes the user's settings.
(set #overwrite-config 1)
(if (exists (tackon #dest "config") (noreq))
    (set #overwrite-config
        (askbool
            (prompt "A config/ folder already exists in\n" #dest "\n\n"
                    "Overwrite it with the shipped defaults?")
            (help "config/ holds Tucan Studio's own settings - fonts, "
                  "editor/git preferences and remembered workspaces. "
                  "Choose NO to KEEP your current settings (recommended "
                  "on an upgrade). Missing config files are still added. "
                  "Choose YES to overwrite files with shipped defaults.")
            (default 0)
        )
    )
)
(if #overwrite-config
    (copyfiles
        (prompt "Copying configuration...")
        (help "Copies the config/ directory to " #dest "/config.")
        (source "config")
        (dest (tackon #dest "config"))
        (all)
    )
    ; Keep existing settings, but add newly shipped files such as screen-size
    ; templates. config/ contains files only; never overwrite a destination.
    (foreach "config" "#?"
        (if (< @each-type 0)
            (if (not (exists (tackon (tackon #dest "config") @each-name) (noreq)))
                (copyfiles
                    (prompt "Adding missing configuration...")
                    (help "Adds new config files while preserving existing settings.")
                    (source (tackon "config" @each-name))
                    (dest (tackon #dest "config"))
                )
            )
        )
    )
)

; help/ — the in-IDE help panel's markdown pages.
(copyfiles
    (prompt "Copying help pages...")
    (help "Copies the help/ directory to " #dest "/help.")
    (source "help")
    (dest (tackon #dest "help"))
    (all)
)

; extension-templates/ — starter files + EXTENSIONS.md for the
; "new extension" flow.
(copyfiles
    (prompt "Copying extension templates...")
    (help "Copies extension-templates/ to " #dest "/extension-templates.")
    (source "extension-templates")
    (dest (tackon #dest "extension-templates"))
    (all)
)

; workspace-templates/ -- the ready-made Workspace menu command sets the
; "Apply workspace template..." picker offers. Without these the picker
; opens empty, which reads as a broken feature rather than a missing
; drawer.
(copyfiles
    (prompt "Copying workspace templates...")
    (help "Copies workspace-templates/ to " #dest "/workspace-templates.")
    (source "workspace-templates")
    (dest (tackon #dest "workspace-templates"))
    (all)
)

; (The extensions/ drawer was created empty above; the IDE's "Manage
; Extensions" flow downloads drawers into it from the registry.)

; S:tucanExtensions — boot scripts directory. The User-Startup
; block iterates files here and Executes each one.
; aminet-cli — the Aminet browser's backend tool, run by the IDE as a
; child process. Lives at the drawer root next to TucanStudio.
(copyfiles
    (prompt "Copying aminet-cli...")
    (help "Copies the aminet-cli tool (Aminet browser backend) to " #dest ".")
    (source "aminet-cli")
    (dest #dest)
    (optional "force")
)

(makedir "S:tucanExtensions"
    (prompt "Creating S:tucanExtensions drawer")
    (help "Per-extension boot scripts will be written here by the "
          "IDE; the User-Startup hook below runs them on every boot.")
)

; --- User-Startup block --------------------------------------------
;
; (startup) edits S:User-Startup and inserts a block bracketed by
; ;BEGIN <name> / ;END <name>. The name MUST be a fixed constant, not
; the drawer name (#dest-name): the Installer only REPLACES a block whose
; name matches, so a variable name (or a reinstall to a different drawer)
; would leave the old block and append a second one. "Tucan Studio" is
; stable across installs, so a reinstall always replaces the one block.
;
; We only set up the tucan: assign — extensions reference their
; install folder as tucan:extensions/<name>/ directly, so no
; second assign is needed.

(startup "Tucan Studio"
    (prompt "Add a Tucan Studio block to S:User-Startup?\n\n"
            "This sets up the tucan: assign and runs every "
            "installed extension's boot script on startup.")
    (help "Without the block, extensions installed from Manage "
          "Extensions won't add themselves to PATH after a reboot "
          "(they will still work for the rest of the current "
          "session). Recommended: yes.")
    ; command strings are concatenated; include explicit line endings.
    (command (cat
        "Assign tucan: \"" #dest "\"\n"
        "If Exists S:tucanExtensions\n"
        "  List S:tucanExtensions FILES LFORMAT \"Execute S:tucanExtensions/%n\" > T:tucan-ext-boot\n"
        "  If Exists T:tucan-ext-boot\n"
        "    Execute T:tucan-ext-boot\n"
        "    Delete >NIL: T:tucan-ext-boot\n"
        "  EndIf\n"
        "EndIf\n"
    ))
)

; Run the assign inside the installer's environment so the path
; becomes available immediately (without forcing a reboot).
; Errors are tolerated — the worst case is the user reboots once.
(run ("Assign tucan: \"%s\"" #dest)
    (safe)
)

; Final message. Putting the text on (exit) gives a single requester
; with just "Proceed" (unlike (message), which also shows "Abort");
; (quiet) suppresses the Installer's stock "…can be found in your
; <volume>: drawer (or partition)" trailer, so there's exactly one
; clean dialog and no bogus "amigaos:" volume line.
(exit "Tucan Studio has been installed.\n\n"
      "Open the " #dest-name " drawer and double-click TucanStudio to start."
      (quiet))
