#!/usr/bin/env sh
set -eu

: "${PACKAGER_NAME=}"

quadVersionNum() {
  num=$(echo "${1:-0}" | cut -d. -f"$2")
  if [ "$num" != "0" ]; then
    echo "${num#0}"
  else
    echo "$num"
  fi
}

. ./scripts/build/.variables

# Create version quad for Windows of the form major.minor.patch.build
VERSION_QUAD=$(printf "%s" "$VERSION" | sed -re 's/^([0-9.]*).*$/\1/' | sed -re 's/\.$//' | sed -re 's/^[0-9]+$/\0\.0/' | sed -re 's/^[0-9]+\.[0-9]+$/\0\.0/' | sed -re 's/^[0-9]+\.[0-9]+\.[0-9]+$/\0\.0/')

# Generate versioninfo.json to be able to create a syso file which contains
# Microsoft Windows Version Information and an icon using goversioninfo.
# https://docs.microsoft.com/en-us/windows/win32/menurc/stringfileinfo-block
# https://github.com/josephspurrier/goversioninfo/blob/v1.5.0/testdata/resource/versioninfo.json
cat > ./cmd/docker/winresources/versioninfo.json <<EOL
{
  "FixedFileInfo":
  {
    "FileVersion": {
      "Major": $(quadVersionNum "$VERSION_QUAD" 1),
      "Minor": $(quadVersionNum "$VERSION_QUAD" 2),
      "Patch": $(quadVersionNum "$VERSION_QUAD" 3),
      "Build": $(quadVersionNum "$VERSION_QUAD" 4)
    },
    "FileFlagsMask": "3f",
    "FileFlags ": "00",
    "FileOS": "040004",
    "FileType": "01",
    "FileSubType": "00"
  },
  "StringFileInfo":
  {
    "Comments": "",
    "CompanyName": "${PACKAGER_NAME}",
    "FileDescription": "Docker Client",
    "FileVersion": "${VERSION}",
    "InternalName": "",
    "LegalCopyright": "Copyright © 2015-$(date +'%Y') Docker Inc.",
    "LegalTrademarks": "",
    "OriginalFilename": "$(basename "${TARGET}")",
    "PrivateBuild": "",
    "ProductName": "Docker Client",
    "ProductVersion": "${VERSION}",
    "SpecialBuild": "${GITCOMMIT}"
  },
  "VarFileInfo":
  {
    "Translation": {
      "LangID": "0409",
      "CharsetID": "04B0"
    }
  }
}
EOL
(set -x ; cat ./cmd/docker/winresources/versioninfo.json)

# Create winresources package stub if removed while using tmpfs in Dockerfile
if [ ! -f "./cmd/docker/winresources/winresources.go" ]; then
  echo "package winresources" > "./cmd/docker/winresources/winresources.go"
fi
