#!/bin/sh
# Print a version string.
scriptversion=2017-01-09.19; # UTC

# Copyright (C) 2007-2017 Free Software Foundation, Inc.
#
# 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 3 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, see <http://www.gnu.org/licenses/>.

# This script is derived from GIT-VERSION-GEN from GIT: http://git.or.cz/.
# It may be run two ways:
# - from a git repository in which the "git describe" command below
#   produces useful output (thus requiring at least one signed tag)
# - from a non-git-repo directory containing a .tarball-version file, which
#   presumes this script is invoked like "./git-version-gen .tarball-version".

# In order to use intra-version strings in your project, you will need two
# separate generated version string files:
#
# .tarball-version - present only in a distribution tarball, and not in
#   a checked-out repository.  Created with contents that were learned at
#   the last time autoconf was run, and used by git-version-gen.  Must not
#   be present in either $(srcdir) or $(builddir) for git-version-gen to
#   give accurate answers during normal development with a checked out tree,
#   but must be present in a tarball when there is no version control system.
#   Therefore, it cannot be used in any dependencies.  GNUmakefile has
#   hooks to force a reconfigure at distribution time to get the value
#   correct, without penalizing normal development with extra reconfigures.
#
# .version - present in a checked-out repository and in a distribution
#   tarball.  Usable in dependencies, particularly for files that don't
#   want to depend on config.h but do want to track version changes.
#   Delete this file prior to any autoconf run where you want to rebuild
#   files to pick up a version string change; and leave it stale to
#   minimize rebuild time after unrelated changes to configure sources.
#
# As with any generated file in a VC'd directory, you should add
# /.version to .gitignore, so that you don't accidentally commit it.
# .tarball-version is never generated in a VC'd directory, so needn't
# be listed there.
#
# Use the following line in your configure.ac, so that $(VERSION) will
# automatically be up-to-date each time configure is run (and note that
# since configure.ac no longer includes a version string, Makefile rules
# should not depend on configure.ac for version updates).
#
# AC_INIT([GNU project],
#         m4_esyscmd([build-aux/git-version-gen .tarball-version]),
#         [bug-project@example])
#
# Then use the following lines in your Makefile.am, so that .version
# will be present for dependencies, and so that .version and
# .tarball-version will exist in distribution tarballs.
#
# EXTRA_DIST = $(top_srcdir)/.version
# BUILT_SOURCES = $(top_srcdir)/.version
# $(top_srcdir)/.version:
#	echo $(VERSION) > $@-t && mv $@-t $@
# dist-hook:
#	echo $(VERSION) > $(distdir)/.tarball-version


me=$0

version="git-version-gen $scriptversion

Copyright 2011 Free Software Foundation, Inc.
There is NO warranty.  You may redistribute this software
under the terms of the GNU General Public License.
For more information about these matters, see the files named COPYING."

usage="\
Usage: $me [OPTION]... \$srcdir/.tarball-version [TAG-NORMALIZATION-SED-SCRIPT]
Print a version string.

Options:

   --prefix PREFIX    prefix of git tags (default 'v')
   --fallback VERSION
                      fallback version to use if \"git --version\" fails

   --help             display this help and exit
   --version          output version information and exit

Running without arguments will suffice in most cases."

prefix=v
fallback=

while test $# -gt 0; do
  case $1 in
    --help) echo "$usage"; exit 0;;
    --version) echo "$version"; exit 0;;
    --prefix) shift; prefix=${1?};;
    --fallback) shift; fallback=${1?};;
    -*)
      echo "$0: Unknown option '$1'." >&2
      echo "$0: Try '--help' for more information." >&2
      exit 1;;
    *)
      if test "x$tarball_version_file" = x; then
        tarball_version_file="$1"
      elif test "x$tag_sed_script" = x; then
        tag_sed_script="$1"
      else
        echo "$0: extra non-option argument '$1'." >&2
        exit 1
      fi;;
  esac
  shift
done

if test "x$tarball_version_file" = x; then
    echo "$usage"
    exit 1
fi

tag_sed_script="${tag_sed_script:-s/x/x/}"

nl='
'

# Avoid meddling by environment variable of the same name.
v=
v_from_git=

# First see if there is a tarball-only version file.
# then try "git describe", then default.
if test -f $tarball_version_file
then
    v=`cat $tarball_version_file` || v=
    case $v in
        *$nl*) v= ;; # reject multi-line output
        [0-9]*) ;;
        *) v= ;;
    esac
    test "x$v" = x \
        && echo "$0: WARNING: $tarball_version_file is missing or damaged" 1>&2
fi

if test "x$v" != x
then
    : # use $v
# Otherwise, if there is at least one git commit involving the working
# directory, and "git describe" output looks sensible, use that to
# derive a version string.
elif test "`git log -1 --pretty=format:x . 2>&1`" = x \
    && v=`git describe --abbrev=4 --match="$prefix*" HEAD 2>/dev/null \
          || git describe --abbrev=4 HEAD 2>/dev/null` \
    && v=`printf '%s\n' "$v" | sed "$tag_sed_script"` \
    && case $v in
         $prefix[0-9]*) ;;
         *) (exit 1) ;;
       esac
then
    # Is this a new git that lists number of commits since the last
    # tag or the previous older version that did not?
    #   Newer: v6.10-77-g0f8faeb
    #   Older: v6.10-g0f8faeb
    case $v in
        *-*-*) : git describe is okay three part flavor ;;
        *-*)
            : git describe is older two part flavor
            # Recreate the number of commits and rewrite such that the
            # result is the same as if we were using the newer version
            # of git describe.
            vtag=`echo "$v" | sed 's/-.*//'`
            commit_list=`git rev-list "$vtag"..HEAD 2>/dev/null` \
                || { commit_list=failed;
                     echo "$0: WARNING: git rev-list failed" 1>&2; }
            numcommits=`echo "$commit_list" | wc -l`
            v=`echo "$v" | sed "s/\(.*\)-\(.*\)/\1-$numcommits-\2/"`;
            test "$commit_list" = failed && v=UNKNOWN
            ;;
    esac

    # Change the first '-' to a '.', so version-comparing tools work properly.
    # Remove the "g" in git describe's output string, to save a byte.
    v=`echo "$v" | sed 's/-/./;s/\(.*\)-g/\1-/'`;
    v_from_git=1
elif test "x$fallback" = x || git --version >/dev/null 2>&1; then
    v=UNKNOWN
else
    v=$fallback
fi

v=`echo "$v" |sed "s/^$prefix//"`

# Test whether to append the "-dirty" suffix only if the version
# string we're using came from git.  I.e., skip the test if it's "UNKNOWN"
# or if it came from .tarball-version.
if test "x$v_from_git" != x; then
  # Don't declare a version "dirty" merely because a timestamp has changed.
  git update-index --refresh > /dev/null 2>&1

  dirty=`exec 2>/dev/null;git diff-index --name-only HEAD` || dirty=
  case "$dirty" in
      '') ;;
      *) # Append the suffix only if there isn't one already.
          case $v in
            *-dirty) ;;
            *) v="$v-dirty" ;;
          esac ;;
  esac
fi

# Omit the trailing newline, so that m4_esyscmd can use the result directly.
printf %s "$v"

# Local variables:
# eval: (add-hook 'write-file-hooks 'time-stamp)
# time-stamp-start: "scriptversion="
# time-stamp-format: "%:y-%02m-%02d.%02H"
# time-stamp-time-zone: "UTC0"
# time-stamp-end: "; # UTC"
# End:
er) (lambda () ((installer-parameters-page current-installer) (lambda _ (#$(compute-keymap-step 'param) current-installer))))) (list ;; Ask the user to choose a locale among those supported by ;; the glibc. Install the selected locale right away, so that ;; the user may benefit from any available translation for the ;; installer messages. (installer-step (id 'locale) (description (G_ "Locale")) (compute (lambda _ (#$locale-step current-installer))) (configuration-formatter locale->configuration)) ;; Welcome the user and ask them to choose between manual ;; installation and graphical install. (installer-step (id 'welcome) (compute (lambda _ ((installer-welcome-page current-installer) #$(local-file "installer/aux-files/logo.txt") #:pci-database #$(file-append pciutils "/share/hwdata/pci.ids.gz"))))) ;; Ask the user to select a timezone under glibc format. (installer-step (id 'timezone) (description (G_ "Timezone")) (compute (lambda _ ((installer-timezone-page current-installer) #$timezone-data))) (configuration-formatter posix-tz->configuration)) ;; The installer runs in a kmscon virtual terminal where loadkeys ;; won't work. kmscon uses libxkbcommon as a backend for keyboard ;; input. It is possible to update kmscon current keymap by sending ;; it a keyboard model, layout, variant and options, in a somehow ;; similar way as what is done with setxkbmap utility. ;; ;; So ask for a keyboard model, layout and variant to update the ;; current kmscon keymap. For non-Latin layouts, we add an ;; appropriate second layout and toggle via Alt+Shift. (installer-step (id 'keymap) (description (G_ "Keyboard mapping selection")) (compute (lambda _ (#$(compute-keymap-step 'default) current-installer))) (configuration-formatter keyboard-layout->configuration)) ;; Ask the user to input a hostname for the system. (installer-step (id 'hostname) (description (G_ "Hostname")) (compute (lambda _ ((installer-hostname-page current-installer)))) (configuration-formatter hostname->configuration)) ;; Provide an interface above connmanctl, so that the user can select ;; a network susceptible to acces Internet. (installer-step (id 'network) (description (G_ "Network selection")) (compute (lambda _ ((installer-network-page current-installer))))) ;; Ask whether to enable substitute server discovery. (installer-step (id 'substitutes) (description (G_ "Substitute server discovery")) (compute (lambda _ ((installer-substitutes-page current-installer))))) ;; Prompt for users (name, group and home directory). (installer-step (id 'user) (description (G_ "User creation")) (compute (lambda _ ((installer-user-page current-installer)))) (configuration-formatter users->configuration)) ;; Ask the user to choose one or many desktop environment(s). (installer-step (id 'services) (description (G_ "Services")) (compute (lambda _ ((installer-services-page current-installer)))) (configuration-formatter system-services->configuration)) ;; Run a partitioning tool allowing the user to modify ;; partition tables, partitions and their mount points. ;; Do this last so the user has something to boot if any ;; of the previous steps didn't go as expected. (installer-step (id 'partition) (description (G_ "Partitioning")) (compute (lambda _ ((installer-partition-page current-installer)))) (configuration-formatter user-partitions->configuration)) (installer-step (id 'final) (description (G_ "Configuration file")) (compute (lambda (result prev-steps) ((installer-final-page current-installer) result prev-steps)))))))) (define (provenance-sexp) "Return an sexp representing the currently-used channels, for logging purposes." (match (match (current-channels) (() (and=> (repository->guix-channel (dirname (current-filename))) list)) (channels channels)) (#f (warning (G_ "cannot determine installer provenance~%")) 'unknown) ((channels ...) (map (lambda (channel) (let* ((uri (string->uri (channel-url channel))) (url (if (or (not uri) (eq? 'file (uri-scheme uri))) "local checkout" (channel-url channel)))) `(channel ,(channel-name channel) ,url ,(channel-commit channel)))) channels)))) (define (installer-program) "Return a file-like object that runs the given INSTALLER." (define init-gettext ;; Initialize gettext support, so that installer messages can be ;; translated. #~(begin (bindtextdomain "guix" (string-append #$guix "/share/locale")) (textdomain "guix") (setlocale LC_ALL ""))) (define set-installer-path ;; Add the specified binary to PATH for later use by the installer. #~(let* ((inputs '#$(list bash ;start subshells connman ;call connmanctl cryptsetup dosfstools ;mkfs.fat e2fsprogs ;mkfs.ext4 lvm2-static ;dmsetup btrfs-progs jfsutils ;jfs_mkfs ntfs-3g ;mkfs.ntfs xfsprogs ;mkfs.xfs kbd ;chvt util-linux ;mkwap nano shadow tar ;dump gzip ;dump coreutils))) (with-output-to-port (%make-void-port "w") (lambda () (set-path-environment-variable "PATH" '("bin" "sbin") inputs))))) (define steps (installer-steps)) (define modules (scheme-modules* (string-append (current-source-directory) "/..") "gnu/installer")) (define installer-builder ;; Note: Include GUIX as an extension to get all the (gnu system …), (gnu ;; packages …), etc. modules. (with-extensions (list guile-gcrypt guile-newt guile-parted guile-bytestructures guile-json-3 guile-git guile-webutils guile-gnutls guile-zlib ;for (gnu build linux-modules) guile-zstd ;for (gnu build linux-modules) (current-guix)) (with-imported-modules `(,@(source-module-closure `(,@modules (gnu services herd) (guix build utils)) #:select? module-to-import?) ((guix config) => ,(make-config.scm))) #~(begin (use-modules (gnu installer record) (gnu installer keymap) (gnu installer steps) (gnu installer dump) (gnu installer final) (gnu installer hostname) (gnu installer locale) (gnu installer parted) (gnu installer services) (gnu installer timezone) (gnu installer user) (gnu installer utils) (gnu installer newt) ((gnu installer newt keymap) #:select (keyboard-layout->configuration)) (gnu services herd) (guix i18n) (guix build utils) ((system repl debug) #:select (terminal-width)) (ice-9 match) (ice-9 textual-ports)) ;; Enable core dump generation. (setrlimit 'core #f #f) (call-with-output-file "/proc/sys/kernel/core_pattern" (lambda (port) (format port %core-dump))) ;; Initialize gettext support so that installers can use ;; (guix i18n) module. #$init-gettext ;; Add some binaries used by the installers to PATH. #$set-installer-path ;; Arrange for language and territory name translations to be ;; available. We need them at run time, not just compile time, ;; because some territories have several corresponding languages ;; (e.g., "French" is always displayed as "français", but ;; "Belgium" could be translated to Dutch, French, or German.) (bindtextdomain "iso_639-3" ;languages #+(file-append iso-codes "/share/locale")) (bindtextdomain "iso_3166-1" ;territories #+(file-append iso-codes "/share/locale")) ;; Likewise for XKB keyboard layout names. (bindtextdomain "xkeyboard-config" #+(file-append xkeyboard-config "/share/locale")) ;; Initialize 'terminal-width' in (system repl debug) ;; to a large-enough value to make backtrace more ;; verbose. (terminal-width 200) (define current-installer newt-installer) (define steps (#$steps current-installer)) (installer-log-line "installer provenance: ~s" '#$(provenance-sexp)) (dynamic-wind (installer-init current-installer) (lambda () (parameterize ((run-command-in-installer (installer-run-command current-installer))) (catch #t (lambda () (define results (run-installer-steps #:rewind-strategy 'menu #:menu-proc (installer-menu-page current-installer) #:steps steps)) (match (result-step results 'final) ('success ;; We did it! Let's reboot! (sync) (stop-service 'root)) (_ ;; The installation failed, exit so that it is ;; restarted by login. #f))) (const #f) (lambda (key . args) (installer-log-line "crashing due to uncaught exception: ~s ~s" key args) (define dump-dir (prepare-dump key args #:result %current-result)) (define user-abort? (match args (((? user-abort-error? obj)) #t) (_ #f))) (define action (if user-abort? 'dump ((installer-exit-error current-installer) (get-string-all (open-input-file (string-append dump-dir "/installer-backtrace")))))) (match action ('dump (let* ((dump-files ((installer-dump-page current-installer) dump-dir)) (dump-archive (make-dump dump-dir dump-files))) ((installer-report-page current-installer) dump-archive))) (_ #f)) (exit 1))))) (installer-exit current-installer)))))) (program-file "installer" #~(begin ;; Set the default locale to install unicode support. For ;; some reason, unicode support is not correctly installed ;; when calling this in 'installer-builder'. (setenv "LANG" "en_US.UTF-8") (execl #$(program-file "installer-real" installer-builder #:guile guile-3.0-latest) "installer-real"))))