echo $(date) " - Starting Node Prep Script"

export USERNAME_ORG=${USERNAME_ORG}
export PASSWORD_ACT_KEY=${PASSWORD_ACT_KEY}
export POOL_ID=${POOL_ID}
export REPOSERVER=${REPOSERVER}
export REGISTRYSERVER=${REGISTRYSERVER}
export PRIVATEIP=${PRIVATEIP}
export ROUTERIP=${ROUTERIP}
export PRIVATEDNS=${PRIVATEDNS}
export INFRADNS=${INFRADNS}
export DEPLOYMENTTYPE=${DEPLOYMENTTYPE}

# Remove RHUI

rm -f /etc/yum.repos.d/*.repo
sleep 10

if [[ ${DEPLOYMENTTYPE} == 3 ]]
then
    # connected
    # Register Host with Cloud Access Subscription
    echo $(date) " - Register host with Cloud Access Subscription"

    subscription-manager register --force --username="${USERNAME_ORG}" --password="${PASSWORD_ACT_KEY}" || subscription-manager register --force --activationkey="${PASSWORD_ACT_KEY}" --org="${USERNAME_ORG}"
    RETCODE=$?

    if [ $RETCODE -eq 0 ]
    then
        echo "Subscribed successfully"
    elif [ $RETCODE -eq 64 ]
    then
        echo "This system is already registered."
    else
    sleep 5
        subscription-manager register --force --username="${USERNAME_ORG}" --password="${PASSWORD_ACT_KEY}" || subscription-manager register --force --activationkey="${PASSWORD_ACT_KEY}" --org="${USERNAME_ORG}"
        RETCODE2=$?
        if [ $RETCODE2 -eq 0 ]
        then
            echo "Subscribed successfully"
        elif [ $RETCODE2 -eq 64 ]
        then
            echo "This system is already registered."
        else
            echo "Incorrect Username / Password or Organization ID / Activation Key specified. Unregistering system from RHSM"
            subscription-manager unregister
            exit 3
        fi
    fi

    subscription-manager attach --pool=${POOL_ID} > attach.log
    if [ $? -eq 0 ]
    then
    echo "Pool attached successfully"
    else
    grep attached attach.log
    if [ $? -eq 0 ]
    then
        echo "Pool ${POOL_ID} was already attached and was not attached again."
    else
        echo "Incorrect Pool ID or no entitlements available"
        exit 4
    fi
    fi

    # Disable all repositories and enable only the required ones
    echo $(date) " - Disabling all repositories and enabling only the required repos"

    subscription-manager repos --disable="*"

    subscription-manager repos \
        --enable="rhel-7-server-rpms" \
        --enable="rhel-7-server-extras-rpms" \
        --enable="rhel-7-server-ose-3.11-rpms" \
        --enable="rhel-7-server-ansible-2.6-rpms" \
        --enable="rhel-7-fast-datapath-rpms" \
        --enable="rh-gluster-3-client-for-rhel-7-server-rpms" \
        --enable="rhel-7-server-optional-rpms"
else

    # wget http://10.3.101.17/ocp-3-11-single-subnet/scripts/ose.repo
    # mv -f ose.repo /etc/yum.repos.d/ose.repo

    # disconnected
cat > /etc/yum.repos.d/ose.repo <<EOF
[rhel-7-repo]
name=rhel-7-repo
baseurl=http://${REPOSERVER}/repos
enabled=1
gpgcheck=0
EOF

fi

# Install base packages and update system to latest packages
echo $(date) " - Install base packages and update system to latest packages"

yum -y install wget git net-tools bind-utils iptables-services bridge-utils bash-completion kexec-tools sos psacct
yum -y install cloud-utils-growpart.noarch
yum -y install ansible
yum -y update glusterfs-fuse
yum -y update --exclude=WALinuxAgent
echo $(date) " - Base package insallation and updates complete"

# Grow Root File System
echo $(date) " - Grow Root FS"

rootdev=`findmnt --target / -o SOURCE -n`
rootdrivename=`lsblk -no pkname $rootdev`
rootdrive="/dev/"$rootdrivename
name=`lsblk  $rootdev -o NAME | tail -1`
part_number=${name#*${rootdrivename}}

growpart $rootdrive $part_number -u on
xfs_growfs $rootdev

# Install Docker
echo $(date) " - Installing Docker"
yum -y install docker

# Update docker config for insecure registry
# echo "
# # Adding insecure-registry option required by OpenShift
# OPTIONS=\"\$OPTIONS --insecure-registry 10.3.103.5:5000\"
# " >> /etc/sysconfig/docker
rm -f /etc/docker/daemon.json
cat > /etc/docker/daemon.json <<EOF
{
  "insecure-registries" : ["${REGISTRYSERVER}","docker-registry-default.${INFRADNS}"]
}
EOF

# Create thin pool logical volume for Docker
echo $(date) " - Creating thin pool logical volume for Docker and starting service"

DOCKERVG=$( parted -m /dev/sda print all 2>/dev/null | grep unknown | grep /dev/sd | cut -d':' -f1 | head -n1 )

echo "
# Adding OpenShift data disk for docker
DEVS=${DOCKERVG}
VG=docker-vg
" >> /etc/sysconfig/docker-storage-setup

# Running setup for docker storage
docker-storage-setup
if [ $? -eq 0 ]
then
    echo "Docker thin pool logical volume created successfully"
else
    echo "Error creating logical volume for Docker"
    exit 5
fi

# Enable and start Docker services

systemctl enable docker
systemctl start docker

# Add DNS host entries for cluster naming
cat >> /etc/hosts <<EOF
${PRIVATEIP} ${PRIVATEDNS}
${ROUTERIP} ${INFRADNS}
EOF

echo $(date) " - Script Complete"


echo $(date) " - Starting Master Prep Script"

export USERNAME_ORG=${USERNAME_ORG}
export PASSWORD_ACT_KEY=${PASSWORD_ACT_KEY}
export POOL_ID=${POOL_ID}
export REPOSERVER=${REPOSERVER}
export REGISTRYSERVER=${REGISTRYSERVER}
export PRIVATEIP=${PRIVATEIP}
export ROUTERIP=${ROUTERIP}
export PRIVATEDNS=${PRIVATEDNS}
export INFRADNS=${INFRADNS}
export DEPLOYMENTTYPE=${DEPLOYMENTTYPE}

# Remove RHUI

rm -f /etc/yum.repos.d/*.repo
sleep 10

if [[ ${DEPLOYMENTTYPE} == 3 ]]
then
    # connected
    # Register Host with Cloud Access Subscription
    echo $(date) " - Register host with Cloud Access Subscription"

    subscription-manager register --force --username="${USERNAME_ORG}" --password="${PASSWORD_ACT_KEY}" || subscription-manager register --force --activationkey="${PASSWORD_ACT_KEY}" --org="${USERNAME_ORG}"
    RETCODE=$?

    if [ $RETCODE -eq 0 ]
    then
        echo "Subscribed successfully"
    elif [ $RETCODE -eq 64 ]
    then
        echo "This system is already registered."
    else
        sleep 5
        subscription-manager register --force --username="${USERNAME_ORG}" --password="${PASSWORD_ACT_KEY}" || subscription-manager register --force --activationkey="${PASSWORD_ACT_KEY}" --org="${USERNAME_ORG}"
        RETCODE2=$?
        if [ $RETCODE2 -eq 0 ]
        then
            echo "Subscribed successfully"
        elif [ $RETCODE2 -eq 64 ]
        then
            echo "This system is already registered."
        else
            echo "Incorrect Username / Password or Organization ID / Activation Key specified. Unregistering system from RHSM"
            subscription-manager unregister
            exit 3
        fi
    fi

    subscription-manager attach --pool=${POOL_ID} > attach.log
    if [ $? -eq 0 ]
    then
        echo "Pool attached successfully"
    else
        grep attached attach.log
        if [ $? -eq 0 ]
        then
            echo "Pool ${POOL_ID} was already attached and was not attached again."
        else
            echo "Incorrect Pool ID or no entitlements available"
            exit 4
    fi
    fi

    # Disable all repositories and enable only the required ones
    echo $(date) " - Disabling all repositories and enabling only the required repos"

    subscription-manager repos --disable="*"

    subscription-manager repos \
        --enable="rhel-7-server-rpms" \
        --enable="rhel-7-server-extras-rpms" \
        --enable="rhel-7-server-ose-3.11-rpms" \
        --enable="rhel-7-server-ansible-2.6-rpms" \
        --enable="rhel-7-fast-datapath-rpms" \
        --enable="rh-gluster-3-client-for-rhel-7-server-rpms" \
        --enable="rhel-7-server-optional-rpms"
else

    # wget http://10.3.101.17/ocp-3-11-single-subnet/scripts/ose.repo
    # mv -f ose.repo /etc/yum.repos.d/ose.repo

    # disconnected
cat > /etc/yum.repos.d/ose.repo <<EOF
[rhel-7-repo]
name=rhel-7-repo
baseurl=http://${REPOSERVER}/repos
enabled=1
gpgcheck=0
EOF

fi

# Install base packages and update system to latest packages
echo $(date) " - Install base packages and update system to latest packages"

yum -y install wget git net-tools bind-utils iptables-services bridge-utils bash-completion httpd-tools kexec-tools sos psacct ansible

#um -y install wget git net-tools bind-utils iptables-services bridge-utils bash-completion httpd-tools kexec-tools sos psacct ansible

yum -y install cloud-utils-growpart.noarch
yum -y update glusterfs-fuse
yum -y update --exclude=WALinuxAgent
echo $(date) " - Base package insallation and updates complete"

# Grow Root File System
echo $(date) " - Grow Root FS"

rootdev=`findmnt --target / -o SOURCE -n`
rootdrivename=`lsblk -no pkname $rootdev`
rootdrive="/dev/"$rootdrivename
name=`lsblk  $rootdev -o NAME | tail -1`
part_number=${name#*${rootdrivename}}

growpart $rootdrive $part_number -u on
xfs_growfs $rootdev

if [ $? -eq 0 ]
then
    echo "Root partition expanded"
else
    echo "Root partition failed to expand"
    exit 6
fi

# Install Docker
echo $(date) " - Installing Docker"
yum -y install docker

# Update docker config for insecure registry
# echo "
# # Adding insecure-registry option required by OpenShift
# OPTIONS=\"\$OPTIONS --insecure-registry 10.3.103.5:5000\"
# " >> /etc/sysconfig/docker
rm -f /etc/docker/daemon.json
cat > /etc/docker/daemon.json <<EOF
{
  "insecure-registries" : ["${REGISTRYSERVER}","docker-registry-default.${INFRADNS}"]
}
EOF

# Create thin pool logical volume for Docker
echo $(date) " - Creating thin pool logical volume for Docker and staring service"

DOCKERVG=$( parted -m /dev/sda print all 2>/dev/null | grep unknown | grep /dev/sd | cut -d':' -f1 )

echo "
# Adding OpenShift data disk for docker
DEVS=${DOCKERVG}
VG=docker-vg
" >> /etc/sysconfig/docker-storage-setup

# Running setup for docker storage
docker-storage-setup
if [ $? -eq 0 ]
then
   echo "Docker thin pool logical volume created successfully"
else
   echo "Error creating logical volume for Docker"
   exit 5
fi

# Enable and start Docker services
sysctl -w vm.max_map_count=262144

systemctl enable docker
systemctl start docker

# Add DNS host entries for cluster naming
cat >> /etc/hosts <<EOF
${PRIVATEIP} ${PRIVATEDNS}
${ROUTERIP} ${INFRADNS}
EOF

echo $(date) " - Script Complete"


echo $(date) " - Starting Infra / Node Prep Script"

export USERNAME_ORG=${USERNAME_ORG}
export PASSWORD_ACT_KEY=${PASSWORD_ACT_KEY}
export POOL_ID=${POOL_ID}
export REPOSERVER=${REPOSERVER}
export REGISTRYSERVER=${REGISTRYSERVER}
export PRIVATEIP=${PRIVATEIP}
export ROUTERIP=${ROUTERIP}
export PRIVATEDNS=${PRIVATEDNS}
export INFRADNS=${INFRADNS}
export DEPLOYMENTTYPE=${DEPLOYMENTTYPE}

# Remove RHUI

rm -f /etc/yum.repos.d/*.repo
sleep 10

if [[ ${DEPLOYMENTTYPE} == 3 ]]
then
    # connected
    # Register Host with Cloud Access Subscription
    echo $(date) " - Register host with Cloud Access Subscription"

    subscription-manager register --force --username="${USERNAME_ORG}" --password="${PASSWORD_ACT_KEY}" || subscription-manager register --force --activationkey="${PASSWORD_ACT_KEY}" --org="${USERNAME_ORG}"
    RETCODE=$?

    if [ $RETCODE -eq 0 ]
    then
        echo "Subscribed successfully"
    elif [ $RETCODE -eq 64 ]
    then
        echo "This system is already registered."
    else
        sleep 5
        subscription-manager register --force --username="${USERNAME_ORG}" --password="${PASSWORD_ACT_KEY}" || subscription-manager register --force --activationkey="${PASSWORD_ACT_KEY}" --org="${USERNAME_ORG}"
        RETCODE2=$?
        if [ $RETCODE2 -eq 0 ]
        then
            echo "Subscribed successfully"
        elif [ $RETCODE2 -eq 64 ]
        then
            echo "This system is already registered."
        else
            echo "Incorrect Username / Password or Organization ID / Activation Key specified. Unregistering system from RHSM"
            subscription-manager unregister
            exit 3
        fi
    fi

    subscription-manager attach --pool=${POOL_ID} > attach.log
    if [ $? -eq 0 ]
    then
        echo "Pool attached successfully"
    else
        grep attached attach.log
        if [ $? -eq 0 ]
        then
            echo "Pool ${POOL_ID} was already attached and was not attached again."
        else
            echo "Incorrect Pool ID or no entitlements available"
            exit 4
        fi
    fi

    # Disable all repositories and enable only the required ones
    echo $(date) " - Disabling all repositories and enabling only the required repos"

    subscription-manager repos --disable="*"

    subscription-manager repos \
        --enable="rhel-7-server-rpms" \
        --enable="rhel-7-server-extras-rpms" \
        --enable="rhel-7-server-ose-3.11-rpms" \
        --enable="rhel-7-server-ansible-2.6-rpms" \
        --enable="rhel-7-fast-datapath-rpms" \
        --enable="rh-gluster-3-client-for-rhel-7-server-rpms" \
        --enable="rhel-7-server-optional-rpms"
else

    # wget http://10.3.101.17/ocp-3-11-single-subnet/scripts/ose.repo
    # mv -f ose.repo /etc/yum.repos.d/ose.repo

    # disconnected
cat > /etc/yum.repos.d/ose.repo <<EOF
[rhel-7-repo]
name=rhel-7-repo
baseurl=http://${REPOSERVER}/repos
enabled=1
gpgcheck=0
EOF

fi

# Install base packages and update system to latest packages
echo $(date) " - Install base packages and update system to latest packages"

yum -y install wget git net-tools bind-utils iptables-services bridge-utils bash-completion kexec-tools sos psacct ansible
yum -y install cloud-utils-growpart.noarch
yum -y update glusterfs-fuse
yum -y update --exclude=WALinuxAgent
echo $(date) " - Base package insallation and updates complete"

# Grow Root File System
echo $(date) " - Grow Root FS"

rootdev=`findmnt --target / -o SOURCE -n`
rootdrivename=`lsblk -no pkname $rootdev`
rootdrive="/dev/"$rootdrivename
name=`lsblk  $rootdev -o NAME | tail -1`
part_number=${name#*${rootdrivename}}

growpart $rootdrive $part_number -u on
xfs_growfs $rootdev

if [ $? -eq 0 ]
then
    echo "Root partition expanded"
else
    echo "Root partition failed to expand"
    exit 6
fi

# Install Docker
echo $(date) " - Installing Docker"
yum -y install docker

# Update docker config for insecure registry
# echo "
# # Adding insecure-registry option required by OpenShift
# OPTIONS=\"\${OPTIONS} --insecure-registry 10.3.103.5:5000\"
# " >> /etc/sysconfig/docker
rm -f /etc/docker/daemon.json
cat > /etc/docker/daemon.json <<EOF
{
  "insecure-registries" : ["${REGISTRYSERVER}","docker-registry-default.${INFRADNS}"]
}
EOF

# Create thin pool logical volume for Docker
echo $(date) " - Creating thin pool logical volume for Docker and staring service"

DOCKERVG=$( parted -m /dev/sda print all 2>/dev/null | grep unknown | grep /dev/sd | cut -d':' -f1 | head -n1 )

echo "
# Adding OpenShift data disk for docker
DEVS=${DOCKERVG}
VG=docker-vg
" >> /etc/sysconfig/docker-storage-setup

# Running setup for docker storage
docker-storage-setup
if [ $? -eq 0 ]
then
    echo "Docker thin pool logical volume created successfully"
else
    echo "Error creating logical volume for Docker"
    exit 5
fi

# Enable and start Docker services
sysctl -w vm.max_map_count=262144

systemctl enable docker
systemctl start docker

# Add DNS host entries for cluster naming
cat >> /etc/hosts <<EOF
${PRIVATEIP} ${PRIVATEDNS}
${ROUTERIP} ${INFRADNS}
EOF

echo $(date) " - Script Complete"


set -e

# only run once during deployment
if [ -f ./azAutomationComplete ]; then
    echo "STIG Automation completed, exiting..."
    exit 0
fi

# https://docs.microsoft.com/en-us/azure/virtual-machines/workloads/redhat/redhat-rhui
id=$(. /etc/os-release && echo $ID)
if [ ${id} == 'rhel' ]; then
    echo "Executing yum update to disable all repos and enable all microsoft repos..."
    yum update -y --disablerepo='*' --enablerepo='*microsoft*' > ./yumupdateresults.log
fi

# dsc deployment automation
echo "Move (OS Specific) .mof to configuration store as Pending.mof..."
mv ./*.mof /etc/opt/omi/conf/dsc/configuration/Pending.mof
echo "Execute Register.py --RefreshMode Push --ConfigurationMode ApplyOnly..."
/opt/microsoft/dsc/Scripts/Register.py --RefreshMode Push --ConfigurationMode ApplyOnly > ./dscresults.log
echo "Execute PerformRequiredConfigurationChecks.py to apply the Pending.mof configuration..."
/opt/microsoft/dsc/Scripts/PerformRequiredConfigurationChecks.py >> ./dscresults.log
if grep -q "MI_RESULT_FAILED" ./dscresults.log; then
    echo "Failed to apply Desired State Configuration successfully, check dscresults.log for more details..."
    exit 1
else
    echo "Applied Desired State Configuration successfully..."
fi

# authentication/password/session automation
echo "Backing up password-auth, postlogin and system-auth files..."
cp --force /etc/pam.d/system-auth /etc/pam.d/backup.system-auth
cp --force /etc/pam.d/password-auth /etc/pam.d/backup.password-auth
cp --force /etc/pam.d/postlogin /etc/pam.d/backup.postlogin
echo "Removing 'nullok' from password-auth and system-auth files..."
sed -i 's/nullok //g' /etc/pam.d/system-auth /etc/pam.d/password-auth
echo "Updating auth pam_faillock.so module in password-auth and system-auth files..."
authRequiredFailDelay='auth        required      pam_faildelay.so delay=2000000'
authRequiredFaillock='auth        required      pam_faillock.so preauth silent audit deny=3 even_deny_root fail_interval=900 unlock_time=900'
authDefaultFaillock='auth        [default=die] pam_faillock.so authfail audit deny=3 even_deny_root fail_interval=900 unlock_time=900'
sed -i "s/\(auth.*sufficient.*pam_fprintd.so\)/${authRequiredFailDelay}/g" /etc/pam.d/system-auth
sed -i "s/\(auth.*delay.*2000000\)/\1\n${authRequiredFaillock}/g" /etc/pam.d/password-auth /etc/pam.d/system-auth
sed -i "s/\(auth.*pam_unix.so.*\)/\1\n${authDefaultFaillock}/g" /etc/pam.d/password-auth /etc/pam.d/system-auth
echo "Updating account pam_faillock.so module in password-auth and system-auth files..."
acctReqPamFaillock='account     required      pam_faillock.so'
sed -i "s/\(account.*pam_unix\.so\)/${acctReqPamFaillock}\n\1/g" /etc/pam.d/password-auth /etc/pam.d/system-auth
echo "Updating password pam_pwhistory.so module in password-auth and system-auth files..."
passReqPamPwHistory='password    requisite     pam_pwhistory.so use_authtok remember=5 retry=3'
sed -i "s/\(password.*requisite.*pam_pwquality\.so.*\)/\1\n${passReqPamPwHistory}/g" /etc/pam.d/password-auth /etc/pam.d/system-auth
echo "Updating session pam_lastlog.so module in /etc/pam.d/postlogin"
sessReqPamLastlog='session     required      pam_lastlog.so showfailed'
sed -i "s/\(session.*quiet\)/${sessReqPamLastlog}\n\1/g" /etc/pam.d/postlogin
echo "Removing 'NOPASSWD' tag from all files in /etc/sudoers.d/* /etc/sudoers"
grep -r -l -i nopasswd /etc/sudoers.d/* /etc/sudoers | xargs sed -i 's/\s*NOPASSWD://g'
echo "Setting minimum number of days before password change for user specified admin account to 1"
chage -m 1 $1
echo "Setting maximum number of days before password change for user specified admin account to 60"
chage -M 60 $1

# file system automation
echo "Setting /home mount to use nosuid in /etc/fstab..."
sed -i "s/\(.*\/home.*defaults\)/\1,nosuid/g" /etc/fstab
echo "Setting tmpfs /dev/shm to mount using nodev, nosuid and noexec in /etc/fstab"
echo 'tmpfs /dev/shm tmpfs defaults,nodev,nosuid,noexec 0 0' >> /etc/fstab

# fips automation
if rpm -q --quiet "dracut-fips"; then
    echo "Recreating initramfs with dracut to support FIPS..."
    dracut --force --verbose 2> ./fipsresults.log
    echo "Modifying grub to support FIPS..."
    BOOT_UUID=$(findmnt --noheadings --output uuid --target /boot)
    sed -i "s/\(GRUB_CMDLINE_LINUX=\".*[^\"]\+\)/\1 fips=1 boot=UUID=${BOOT_UUID}/g" /etc/default/grub
    if [ -f /boot/grub2/grub.cfg ]; then
        echo "Regenerating /boot/grub2/grub.cfg (BIOS)..."
        grub2-mkconfig -o /boot/grub2/grub.cfg 2>> ./fipsresults.log
    fi
    if [ -f /boot/efi/EFI/centos/grub.cfg ]; then
        echo "Regenerating /boot/efi/EFI/centos/grub.cfg (UEFI)..."
        grub2-mkconfig -o /boot/efi/EFI/centos/grub.cfg 2>> ./fipsresults.log
    elif [ -f /boot/efi/EFI/redhat/grub.cfg ]; then
        echo "Regenerating /boot/efi/EFI/redhat/grub.cfg (UEFI)..."
        grub2-mkconfig -o /boot/efi/EFI/redhat/grub.cfg 2>> ./fipsresults.log
    else
        echo "Skipping grub2-mkconfig for UEFI, no EFI grub.cfg file found..."
    fi
else
    echo "Skipping fips automation due to dracut-fips package installation absence..."
fi

# aide configuration automation
if rpm -q --quiet "aide"; then
    echo "Modifying /etc/aide.conf to use sha512..."
    sed -i 's/CONTENT_EX = sha256/CONTENT_EX = sha512/g' /etc/aide.conf
    echo "Executing /usr/sbin/aide --init..."
    /usr/sbin/aide --init > aideresults.log
    echo "Moving /var/lib/aide/aide.db.new.gz to /var/lib/aide/aide.db.gz..."
    mv --verbose --force /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz
    echo "Adding aide daily check cron job..."
    echo '0 5 * * * root /usr/sbin/aide --check | /bin/mail -s "$(hostname) - AIDE Integrity Check" root@localhost' > /etc/cron.daily/aide
else
    echo "Skipping aide automation due to aide package installation absence..."
fi

# system reboot
echo "Rebooting to apply STIG settings..."
touch ./azAutomationComplete
shutdown -r +1 2>&1


# only run once during deployment
if [ -f ./azAutomationComplete ]; then
    echo "STIG Automation completion detected, exiting..."
    exit 0
fi

# apt-get update to assist nxPackage dsc automation
echo "Executing apt-get update..."
apt-get update -q > ./aptgetupdateresults.log

set -e

# dsc deployment automation
echo "Move (OS Specific) .mof to configuration store as Pending.mof..."
mv ./*.mof /etc/opt/omi/conf/dsc/configuration/Pending.mof
echo "Execute Register.py --RefreshMode Push --ConfigurationMode ApplyOnly..."
/opt/microsoft/dsc/Scripts/Register.py --RefreshMode Push --ConfigurationMode ApplyOnly > ./dscresults.log
echo "Execute PerformRequiredConfigurationChecks.py to apply the Pending.mof configuration..."
/opt/microsoft/dsc/Scripts/PerformRequiredConfigurationChecks.py >> ./dscresults.log
if grep -q "MI_RESULT_FAILED" ./dscresults.log; then
    echo "Failed to apply Desired State Configuration successfully, check dscresults.log for more details..."
    exit 1
else
    echo "Applied Desired State Configuration successfully..."
fi

# authentication/password/session automation
echo "Creating /etc/pam.d/common-password to meet STIG requirements..."
mv --force /etc/pam.d/common-password /etc/pam.d/backup.common-password
echo "# Generated by Microsoft.Azure.Extensions/CustomScript" > /etc/pam.d/common-password
echo "# Original common-password was moved to /etc/pam.d/backup.common-password" >> /etc/pam.d/common-password
echo "password\trequisite\t\t\tpam_pwquality.so retry=3 enforce_for_root" >> /etc/pam.d/common-password
echo "password\t[success=1 default=ignore]\tpam_unix.so obscure sha512 shadow remember=5 rounds=5000" >> /etc/pam.d/common-password
echo "password\trequired\t\t\tpam_permit.so" >> /etc/pam.d/common-password
echo "Creating /etc/pam.d/common-auth to meet STIG requirements..."
mv --force /etc/pam.d/common-auth /etc/pam.d/backup.common-auth
echo "# Generated by Microsoft.Azure.Extensions/CustomScript" > /etc/pam.d/common-auth
echo "# Original common-auth was moved to /etc/pam.d/backup.common-auth" >> /etc/pam.d/common-auth
echo "auth\trequired\t\t\tpam_tally2.so onerr=fail deny=3" >> /etc/pam.d/common-auth
echo "auth\trequired\t\t\tpam_faildelay.so delay=4000000" >> /etc/pam.d/common-auth
echo "auth\t[success=1 default=ignore]\tpam_unix.so nullok_secure" >> /etc/pam.d/common-auth
echo "auth\trequisite\t\t\tpam_deny.so" >> /etc/pam.d/common-auth
echo "auth\trequired\t\t\tpam_permit.so" >> /etc/pam.d/common-auth
echo "auth\toptional\t\t\tpam_cap.so" >> /etc/pam.d/common-auth
echo "# auth\t[success=2 default=ignore]\tpam_pkcs11.so" >> /etc/pam.d/common-auth
echo "Adding 'session required pam_lastlog.so showfailed' after session pam_selinux.so module in /etc/pam.d/login..."
sed -i 's/\(session.*pam_selinux\.so close\)/\1\nsession required pam_lastlog.so showfailed/g' /etc/pam.d/login
echo "Removing 'NOPASSWD' tag from all files in /etc/sudors.d/"
grep -r -l -i nopasswd /etc/sudoers.d/* | xargs sed -i 's/\s*NOPASSWD://g'
echo "Executing useradd -D -f 35..."
useradd -D -f 35

# file system permissions automation
echo "Setting permissions to all log files under /far/log to 640..."
find /var/log -perm /137 -type f -exec chmod -c 640 '{}' \;
echo "Setting mode to 0750 for /var/log..."
chmod -c 0750 /var/log
echo "Setting group ownership to root for /lib, /usr/lib and /lib64..."
find /lib /usr/lib /lib64 ! -group root -type f -exec chgrp -c root '{}' \;
echo "Setting ownership to root for /bin, /sbin, /usr/bin, /usr/sbin, /usr/local/bin and /usr/local/sbin..."
set +e
find -L /bin /sbin /usr/bin /usr/sbin /usr/local/bin /usr/local/sbin ! -user root -type f -exec chown -c root '{}' \;
echo "Setting group ownership to root for /bin, /sbin, /usr/bin, /usr/sbin, /usr/local/bin and /usr/local/sbin..."
find -L /bin /sbin /usr/bin /usr/sbin /usr/local/bin /usr/local/sbin ! -group root -type f -exec chgrp -c root '{}' \;
set -e
echo "Setting mode to 0600 for /var/log/audit/*..."
chmod -c 0600 /var/log/audit/*

# chmod persistent cloud-init per-boot script
if [ ! -f /var/lib/cloud/scripts/per-boot/per-boot.sh ]; then
    echo "Writing /var/lib/cloud/scripts/per-boot/per-boot.sh to address chmod persistence post reboot..."
    echo '#!/bin/bash' > /var/lib/cloud/scripts/per-boot/per-boot.sh
    echo 'echo $(date) > /var/log/cloud-init-per-boot.log' >> /var/lib/cloud/scripts/per-boot/per-boot.sh
    echo 'find /var/log -perm /137 -type f -exec chmod -c 640 '{}' \; >> /var/log/cloud-init-per-boot.log' >> /var/lib/cloud/scripts/per-boot/per-boot.sh
    echo 'chmod -c 0750 /var/log >> /var/log/cloud-init-per-boot.log' >> /var/lib/cloud/scripts/per-boot/per-boot.sh
    echo 'chmod -c 0600 /var/log/audit/* >> /var/log/cloud-init-per-boot.log' >> /var/lib/cloud/scripts/per-boot/per-boot.sh
    chmod +x /var/lib/cloud/scripts/per-boot/per-boot.sh
fi

# boot / audit automation
echo "Adding 'audit=1' to /etc/default/grub to enable auditing at system startup..."
cp --force /etc/default/grub /etc/default/backup.grub
sed -i 's/\(GRUB_CMDLINE_LINUX="\)/\1audit=1/g' /etc/default/grub
update-grub 2> ./updategrubresults.log

# system reboot
echo "Rebooting to apply STIG settings..."
touch ./azAutomationComplete
shutdown -r +1 2>&1


# only run once during deployment
if [ -f ./azAutomationComplete ]; then
    echo "STIG Automation completion detected, exiting..."
    exit 0
fi

# apt-get update to assist nxPackage dsc automation
echo "Executing apt-get update..."
apt-get update -q > ./aptgetupdateresults.log

set -e

# dsc deployment automation
echo "Move (OS Specific) .mof to configuration store as Pending.mof..."
mv ./*.mof /etc/opt/omi/conf/dsc/configuration/Pending.mof
echo "Execute Register.py --RefreshMode Push --ConfigurationMode ApplyOnly..."
/opt/microsoft/dsc/Scripts/Register.py --RefreshMode Push --ConfigurationMode ApplyOnly > ./dscresults.log
echo "Execute PerformRequiredConfigurationChecks.py to apply the Pending.mof configuration..."
/opt/microsoft/dsc/Scripts/PerformRequiredConfigurationChecks.py >> ./dscresults.log
if grep -q "MI_RESULT_FAILED" ./dscresults.log; then
    echo "Failed to apply Desired State Configuration successfully, check dscresults.log for more details..."
    exit 1
else
    echo "Applied Desired State Configuration successfully..."
fi

# authentication/password/session automation
echo "Creating /etc/pam.d/common-password to meet STIG requirements..."
mv --force /etc/pam.d/common-password /etc/pam.d/backup.common-password
echo "# Generated by Microsoft.Azure.Extensions/CustomScript" > /etc/pam.d/common-password
echo "# Original common-password was moved to /etc/pam.d/backup.common-password" >> /etc/pam.d/common-password
echo "password\trequisite\t\t\tpam_pwquality.so retry=3 enforce_for_root" >> /etc/pam.d/common-password
echo "password\t[success=1 default=ignore]\tpam_unix.so obscure sha512 shadow remember=5 rounds=5000" >> /etc/pam.d/common-password
echo "password\trequired\t\t\tpam_permit.so" >> /etc/pam.d/common-password
echo "Creating /etc/pam.d/common-auth to meet STIG requirements..."
mv --force /etc/pam.d/common-auth /etc/pam.d/backup.common-auth
echo "# Generated by Microsoft.Azure.Extensions/CustomScript" > /etc/pam.d/common-auth
echo "# Original common-auth was moved to /etc/pam.d/backup.common-auth" >> /etc/pam.d/common-auth
echo "auth\trequired\t\t\tpam_tally2.so onerr=fail deny=3" >> /etc/pam.d/common-auth
echo "auth\trequired\t\t\tpam_faildelay.so delay=4000000" >> /etc/pam.d/common-auth
echo "auth\t[success=1 default=ignore]\tpam_unix.so nullok_secure" >> /etc/pam.d/common-auth
echo "auth\trequisite\t\t\tpam_deny.so" >> /etc/pam.d/common-auth
echo "auth\trequired\t\t\tpam_permit.so" >> /etc/pam.d/common-auth
echo "auth\toptional\t\t\tpam_cap.so" >> /etc/pam.d/common-auth
echo "# auth\t[success=2 default=ignore]\tpam_pkcs11.so" >> /etc/pam.d/common-auth
echo "Adding 'session required pam_lastlog.so showfailed' after session pam_selinux.so module in /etc/pam.d/login..."
sed -i 's/\(session.*pam_selinux\.so close\)/\1\nsession required pam_lastlog.so showfailed/g' /etc/pam.d/login
echo "Removing 'NOPASSWD' tag from all files in /etc/sudors.d/"
grep -r -l -i nopasswd /etc/sudoers.d/* | xargs sed -i 's/\s*NOPASSWD://g'
echo "Executing useradd -D -f 35..."
useradd -D -f 35

# file system permissions automation
echo "Setting permissions to all log files under /far/log to 640..."
find /var/log -perm /137 -type f -exec chmod -c 640 '{}' \;
echo "Setting mode to 0750 for /var/log..."
chmod -c 0750 /var/log
echo "Setting group ownership to root for /lib, /usr/lib and /lib64..."
find /lib /usr/lib /lib64 ! -group root -type f -exec chgrp -c root '{}' \;
echo "Setting ownership to root for /bin, /sbin, /usr/bin, /usr/sbin, /usr/local/bin and /usr/local/sbin..."
find -L /bin /sbin /usr/bin /usr/sbin /usr/local/bin /usr/local/sbin ! -user root -type f -exec chown -c root '{}' \;
echo "Setting group ownership to root for /bin, /sbin, /usr/bin, /usr/sbin, /usr/local/bin and /usr/local/sbin..."
find -L /bin /sbin /usr/bin /usr/sbin /usr/local/bin /usr/local/sbin ! -group root -type f -exec chgrp -c root '{}' \;
echo "Setting mode to 0600 for /var/log/audit/*..."
chmod -c 0600 /var/log/audit/*

# chmod persistent cloud-init per-boot script
if [ ! -f /var/lib/cloud/scripts/per-boot/per-boot.sh ]; then
    echo "Writing /var/lib/cloud/scripts/per-boot/per-boot.sh to address chmod persistence post reboot..."
    echo '#!/bin/bash' > /var/lib/cloud/scripts/per-boot/per-boot.sh
    echo 'echo $(date) > /var/log/cloud-init-per-boot.log' >> /var/lib/cloud/scripts/per-boot/per-boot.sh
    echo 'find /var/log -perm /137 -type f -exec chmod -c 640 '{}' \; >> /var/log/cloud-init-per-boot.log' >> /var/lib/cloud/scripts/per-boot/per-boot.sh
    echo 'chmod -c 0750 /var/log >> /var/log/cloud-init-per-boot.log' >> /var/lib/cloud/scripts/per-boot/per-boot.sh
    echo 'chmod -c 0600 /var/log/audit/* >> /var/log/cloud-init-per-boot.log' >> /var/lib/cloud/scripts/per-boot/per-boot.sh
    chmod +x /var/lib/cloud/scripts/per-boot/per-boot.sh
fi

# boot / audit automation
echo "Adding 'audit=1' to /etc/default/grub to enable auditing at system startup..."
cp --force /etc/default/grub /etc/default/backup.grub
sed -i 's/\(GRUB_CMDLINE_LINUX="\)/\1audit=1/g' /etc/default/grub
update-grub 2> ./updategrubresults.log

# system reboot
echo "Rebooting to apply STIG settings..."
touch ./azAutomationComplete
shutdown -r +1 2>&1


# set up variables needed
workingFolder="/var/tmp/zta-files"
archive="offline-zta.tar.gz"
offlineRepoName="offline-zta-repo"
stigFile="rhel7.sh"

# create the working folder
echo "..creating the working folder: $workingFolder"
mkdir $workingFolder

# uncompress the archive
echo "..uncompressing archive to: $workingFolder"
tar -xzvf "$archive" -C "$workingFolder"

# create an entry for the repo
echo "..creating repo file: /etc/yum.repos.d/$offlineRepoName.repo"
cat > /etc/yum.repos.d/$offlineRepoName.repo<< EOF
[offline-zta-repo]
name=$offlineRepoName
baseurl=file:///$workingFolder/$offlineRepoName
enabled=0
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
EOF

# run the stig script
echo "..executing stig script: $stigFile"
bash "$stigFile"

# remove the repo file and working folder
echo "..stig script done. Time for cleanup"
echo "..removing repo file: /etc/yum.repos.d/$offlineRepoName.repo"
rm -f /etc/yum.repos.d/$offlineRepoName.repo
echo "..removing working folder: $workingFolder"
rm -r $workingFolder


stigFile="rhel7.sh"

# run the stig script
echo "..executing stig script: $stigFile"
bash "$stigFile"


# Script to deploy the app
# This file is needed only when you want to deploy the app to a Linux VM

# install node
pushd .
cd ~
curl -sL https://deb.nodesource.com/setup_6.x -o nodesource_setup.sh
sudo bash nodesource_setup.sh
sudo apt-get install nodejs -y
sudo apt-get install build-essential -y

# install express
sudo npm install express -y -g
popd

# configure nginx
sudo rm -f /etc/nginx/sites-enabled/default
sudo cp -f ./nginx-config /etc/nginx/sites-available/example
sudo ln -fs /etc/nginx/sites-available/example /etc/nginx/sites-enabled
sudo service nginx reload

# install pm2 and start the node server as a daemon
cd ..
sudo npm install pm2 -g -y
pm2 delete example -s
pm2 start server.js -n example


# Test driver script to be used in a container
# See http://docs.microsoft.com/azure/devops/pipelines/languages/docker for more information
sleep 5
if curl web | grep -q 'Hello world'; then
  echo "Tests passed!"
  exit 0
else
  echo "Tests failed!"
  exit 1
fi


#!/bin/bash
set -x;

docker build -t azsdkengsys.azurecr.io/azuresdk/autorest --build-arg REGISTRY="mcr.microsoft.com/mirror/docker/library/" ./base/ubuntu
docker build -t azsdkengsys.azurecr.io/azuresdk/autorest-dotnet ./dotnet/ubuntu
docker build -t azsdkengsys.azurecr.io/azuresdk/autorest-python ./python/ubuntu
docker build -t azsdkengsys.azurecr.io/azuresdk/autorest-java ./java/ubuntu
docker build -t azsdkengsys.azurecr.io/azuresdk/autorest-all ./all/ubuntu


# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

export SPEC_REPO=https://github.com/Azure/azure-rest-api-specs.git
export TSP_PATH=specification/eventgrid/Azure.Messaging.EventGrid
export REPO_BRANCH=feature/eventgrid/typespec

mkdir tsp-repo
cd tsp-repo
git init
git config core.sparseCheckout true
git remote add -f origin $SPEC_REPO
echo $TSP_PATH > .git/info/sparse-checkout
git checkout $REPO_BRANCH
cd ..

cp -rf tsp-repo/$TSP_PATH tsp-src
rm -rf tsp-repo


#!/bin/bash

cd ./.build/checkouts/SwiftLint/Source/swiftlint
swift build

cd ../../../../..


#!/bin/bash

# git_sync.sh

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
REPO_ROOT="$( cd -P "$( dirname "$SOURCE" )"/.. >/dev/null 2>&1 && pwd )"

# TODO: make this not hard coded
SDK_REPO_ROOT="/Users/travisprescott/repos/azure-sdk-for-ios/"
SDK_PACKAGE_ROOT="/Users/travisprescott/repos/azure-sdk-for-ios/sdk/communication/"
SDK_SRC="/Users/travisprescott/Documents/generated/sdk"

# FIXME: The build step fails when run with makefile.
#echo
#echo "AutoRest.Swift root: $REPO_ROOT"
#echo
#echo "==~ Building AutoRest.Swift ~=="
#echo
#make build -C $REPO_ROOT
#echo
#echo "==~ Generating SDK ~=="
#echo
#swift run --package-path $REPO_ROOT

echo
echo "==~ Copying generated code to azure-sdk-for-ios ~=="
PACKAGE_NAME=$(ls  -1 -t $SDK_SRC | head -1)

# copy the jazzy files from the generated package into the SDK root
cp -r $SDK_SRC/$PACKAGE_NAME/.jazzy/ $SDK_REPO_ROOT/.jazzy

# copy the generated code into the SDK repo
cp -rf $SDK_SRC/. $SDK_PACKAGE_ROOT

echo
echo "Switching to: " $SDK_REPO_ROOT
cd $SDK_REPO_ROOT

echo
echo "Checking out feature/communication branch"
git reset
git checkout feature/communication

cd $REPO_ROOT

echo "==~ Ready to Commit Changes in SourceTree! ~=="


#!/bin/bash

#  swiftlint.sh
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
REPO_ROOT="$( cd -P "$( dirname "$SOURCE" )"/.. >/dev/null 2>&1 && pwd )"

echo
echo "Repo root: $REPO_ROOT"
echo

if which swiftformat >/dev/null; then
    echo "Formatting Swift files at: $REPO_ROOT/src"
    swiftformat --quiet --config "$REPO_ROOT/.swiftformat" "$REPO_ROOT/src" &> /dev/null
    echo "Formatting Swift files at: $REPO_ROOT/AutorestSwiftTest"
    swiftformat --quiet --config "$REPO_ROOT/.swiftformat" "$REPO_ROOT/AutorestSwiftTest" &> /dev/null
else
    echo "warning: SwiftFormat not installed. Download from https://github.com/nicklockwood/SwiftFormat"
fi

if which swiftlint >/dev/null; then
    echo "Correcting Swift files at: $REPO_ROOT/src"
    swiftlint autocorrect --quiet --config "$REPO_ROOT/.swiftlint.yml" "$REPO_ROOT/src" &> /dev/null
    echo "Linting Swift files at: $REPO_ROOT/src"
    swiftlint lint --quiet --config "$REPO_ROOT/.swiftlint.yml" "$REPO_ROOT/src"
    echo "Correcting Swift files at: $REPO_ROOT/AutorestSwiftTest"
    swiftlint autocorrect --quiet --config "$REPO_ROOT/.swiftlint.yml" "$REPO_ROOT/AutorestSwiftTest" &> /dev/null
    echo "Linting Swift files at: $REPO_ROOT/AutorestSwiftTest"
    swiftlint lint --quiet --config "$REPO_ROOT/.swiftlint.yml" "$REPO_ROOT/AutorestSwiftTest"
else
    echo "warning: SwiftLint not installed. Download from https://github.com/realm/SwiftLint"
fi


go get github.com/golang/protobuf/protoc-gen-go

protoc \
--go_out=Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any:. *.proto


#!/bin/bash
set -e
set -x

if [ ! -d /tmp/build-golang/src/github.com/json-iterator ]; then
    mkdir -p /tmp/build-golang/src/github.com/json-iterator
    ln -s $PWD /tmp/build-golang/src/github.com/json-iterator/go
fi
export GOPATH=/tmp/build-golang
go get -u github.com/golang/dep/cmd/dep
cd /tmp/build-golang/src/github.com/json-iterator/go
exec $GOPATH/bin/dep ensure -update


#!/usr/bin/env bash

set -e
echo "" > coverage.txt

for d in $(go list ./... | grep -v vendor); do
    go test -coverprofile=profile.out -coverpkg=github.com/json-iterator/go $d
    if [ -f profile.out ]; then
        cat profile.out >> coverage.txt
        rm profile.out
    fi
done


#!/usr/bin/env bash

set -e
echo "" > coverage.txt

for d in $(go list ./... | grep -v vendor); do
    go test -coverprofile=profile.out -coverpkg=github.com/modern-go/concurrent $d
    if [ -f profile.out ]; then
        cat profile.out >> coverage.txt
        rm profile.out
    fi
done


#!/usr/bin/env bash

set -e
echo "" > coverage.txt

for d in $(go list ./... | grep -v vendor); do
    go test -coverprofile=profile.out -coverpkg=github.com/modern-go/reflect2 $d
    if [ -f profile.out ]; then
        cat profile.out >> coverage.txt
        rm profile.out
    fi
done


#!/usr/bin/env bash
# Copyright 2009 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.

# This script runs or (given -n) prints suggested commands to generate files for
# the Architecture/OS specified by the GOARCH and GOOS environment variables.
# See README.md for more information about how the build system works.

GOOSARCH="${GOOS}_${GOARCH}"

# defaults
mksyscall="./mksyscall.pl"
mkerrors="./mkerrors.sh"
zerrors="zerrors_$GOOSARCH.go"
mksysctl=""
zsysctl="zsysctl_$GOOSARCH.go"
mksysnum=
mktypes=
run="sh"
cmd=""

case "$1" in
-syscalls)
	for i in zsyscall*go
	do
		# Run the command line that appears in the first line
		# of the generated file to regenerate it.
		sed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i
		rm _$i
	done
	exit 0
	;;
-n)
	run="cat"
	cmd="echo"
	shift
esac

case "$#" in
0)
	;;
*)
	echo 'usage: mkall.sh [-n]' 1>&2
	exit 2
esac

if [[ "$GOOS" = "linux" ]] && [[ "$GOARCH" != "sparc64" ]]; then
	# Use then new build system
	# Files generated through docker (use $cmd so you can Ctl-C the build or run)
	$cmd docker build --tag generate:$GOOS $GOOS
	$cmd docker run --interactive --tty --volume $(dirname "$(readlink -f "$0")"):/build generate:$GOOS
	exit
fi

GOOSARCH_in=syscall_$GOOSARCH.go
case "$GOOSARCH" in
_* | *_ | _)
	echo 'undefined $GOOS_$GOARCH:' "$GOOSARCH" 1>&2
	exit 1
	;;
darwin_386)
	mkerrors="$mkerrors -m32"
	mksyscall="./mksyscall.pl -l32"
	mksysnum="./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
darwin_amd64)
	mkerrors="$mkerrors -m64"
	mksysnum="./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
darwin_arm)
	mkerrors="$mkerrors"
	mksysnum="./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
darwin_arm64)
	mkerrors="$mkerrors -m64"
	mksysnum="./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
dragonfly_386)
	mkerrors="$mkerrors -m32"
	mksyscall="./mksyscall.pl -l32 -dragonfly"
	mksysnum="curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
dragonfly_amd64)
	mkerrors="$mkerrors -m64"
	mksyscall="./mksyscall.pl -dragonfly"
	mksysnum="curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
freebsd_386)
	mkerrors="$mkerrors -m32"
	mksyscall="./mksyscall.pl -l32"
	mksysnum="curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
freebsd_amd64)
	mkerrors="$mkerrors -m64"
	mksysnum="curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
freebsd_arm)
	mkerrors="$mkerrors"
	mksyscall="./mksyscall.pl -l32 -arm"
	mksysnum="curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl"
	# Let the type of C char be signed for making the bare syscall
	# API consistent across platforms.
	mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
	;;
linux_sparc64)
	GOOSARCH_in=syscall_linux_sparc64.go
	unistd_h=/usr/include/sparc64-linux-gnu/asm/unistd.h
	mkerrors="$mkerrors -m64"
	mksysnum="./mksysnum_linux.pl $unistd_h"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
netbsd_386)
	mkerrors="$mkerrors -m32"
	mksyscall="./mksyscall.pl -l32 -netbsd"
	mksysnum="curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
netbsd_amd64)
	mkerrors="$mkerrors -m64"
	mksyscall="./mksyscall.pl -netbsd"
	mksysnum="curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
netbsd_arm)
	mkerrors="$mkerrors"
	mksyscall="./mksyscall.pl -l32 -netbsd -arm"
	mksysnum="curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl"
	# Let the type of C char be signed for making the bare syscall
	# API consistent across platforms.
	mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
	;;
openbsd_386)
	mkerrors="$mkerrors -m32"
	mksyscall="./mksyscall.pl -l32 -openbsd"
	mksysctl="./mksysctl_openbsd.pl"
	mksysnum="curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
openbsd_amd64)
	mkerrors="$mkerrors -m64"
	mksyscall="./mksyscall.pl -openbsd"
	mksysctl="./mksysctl_openbsd.pl"
	mksysnum="curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
openbsd_arm)
	mkerrors="$mkerrors"
	mksyscall="./mksyscall.pl -l32 -openbsd -arm"
	mksysctl="./mksysctl_openbsd.pl"
	mksysnum="curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl"
	# Let the type of C char be signed for making the bare syscall
	# API consistent across platforms.
	mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
	;;
solaris_amd64)
	mksyscall="./mksyscall_solaris.pl"
	mkerrors="$mkerrors -m64"
	mksysnum=
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
*)
	echo 'unrecognized $GOOS_$GOARCH: ' "$GOOSARCH" 1>&2
	exit 1
	;;
esac

(
	if [ -n "$mkerrors" ]; then echo "$mkerrors |gofmt >$zerrors"; fi
	case "$GOOS" in
	*)
		syscall_goos="syscall_$GOOS.go"
		case "$GOOS" in
		darwin | dragonfly | freebsd | netbsd | openbsd)
			syscall_goos="syscall_bsd.go $syscall_goos"
			;;
		esac
		if [ -n "$mksyscall" ]; then echo "$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go"; fi
		;;
	esac
	if [ -n "$mksysctl" ]; then echo "$mksysctl |gofmt >$zsysctl"; fi
	if [ -n "$mksysnum" ]; then echo "$mksysnum |gofmt >zsysnum_$GOOSARCH.go"; fi
	if [ -n "$mktypes" ]; then
		echo "$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go";
	fi
) | $run


#!/usr/bin/env bash
# Copyright 2009 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.

# Generate Go code listing errors and other #defined constant
# values (ENAMETOOLONG etc.), by asking the preprocessor
# about the definitions.

unset LANG
export LC_ALL=C
export LC_CTYPE=C

if test -z "$GOARCH" -o -z "$GOOS"; then
	echo 1>&2 "GOARCH or GOOS not defined in environment"
	exit 1
fi

# Check that we are using the new build system if we should
if [[ "$GOOS" = "linux" ]] && [[ "$GOARCH" != "sparc64" ]]; then
	if [[ "$GOLANG_SYS_BUILD" != "docker" ]]; then
		echo 1>&2 "In the new build system, mkerrors should not be called directly."
		echo 1>&2 "See README.md"
		exit 1
	fi
fi

CC=${CC:-cc}

if [[ "$GOOS" = "solaris" ]]; then
	# Assumes GNU versions of utilities in PATH.
	export PATH=/usr/gnu/bin:$PATH
fi

uname=$(uname)

includes_Darwin='
#define _DARWIN_C_SOURCE
#define KERNEL
#define _DARWIN_USE_64_BIT_INODE
#include <sys/types.h>
#include <sys/event.h>
#include <sys/ptrace.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/sysctl.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/wait.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/route.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <termios.h>
'

includes_DragonFly='
#include <sys/types.h>
#include <sys/event.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/sysctl.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/route.h>
#include <netinet/in.h>
#include <termios.h>
#include <netinet/ip.h>
#include <net/ip_mroute/ip_mroute.h>
'

includes_FreeBSD='
#include <sys/capability.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/event.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/sysctl.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/route.h>
#include <netinet/in.h>
#include <termios.h>
#include <netinet/ip.h>
#include <netinet/ip_mroute.h>
#include <sys/extattr.h>

#if __FreeBSD__ >= 10
#define IFT_CARP	0xf8	// IFT_CARP is deprecated in FreeBSD 10
#undef SIOCAIFADDR
#define SIOCAIFADDR	_IOW(105, 26, struct oifaliasreq)	// ifaliasreq contains if_data
#undef SIOCSIFPHYADDR
#define SIOCSIFPHYADDR	_IOW(105, 70, struct oifaliasreq)	// ifaliasreq contains if_data
#endif
'

includes_Linux='
#define _LARGEFILE_SOURCE
#define _LARGEFILE64_SOURCE
#ifndef __LP64__
#define _FILE_OFFSET_BITS 64
#endif
#define _GNU_SOURCE

// <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of
// these structures. We just include them copied from <bits/termios.h>.
#if defined(__powerpc__)
struct sgttyb {
        char    sg_ispeed;
        char    sg_ospeed;
        char    sg_erase;
        char    sg_kill;
        short   sg_flags;
};

struct tchars {
        char    t_intrc;
        char    t_quitc;
        char    t_startc;
        char    t_stopc;
        char    t_eofc;
        char    t_brkc;
};

struct ltchars {
        char    t_suspc;
        char    t_dsuspc;
        char    t_rprntc;
        char    t_flushc;
        char    t_werasc;
        char    t_lnextc;
};
#endif

#include <bits/sockaddr.h>
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <sys/inotify.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/xattr.h>
#include <linux/if.h>
#include <linux/if_alg.h>
#include <linux/if_arp.h>
#include <linux/if_ether.h>
#include <linux/if_tun.h>
#include <linux/if_packet.h>
#include <linux/if_addr.h>
#include <linux/falloc.h>
#include <linux/filter.h>
#include <linux/fs.h>
#include <linux/keyctl.h>
#include <linux/netlink.h>
#include <linux/perf_event.h>
#include <linux/random.h>
#include <linux/reboot.h>
#include <linux/rtnetlink.h>
#include <linux/ptrace.h>
#include <linux/sched.h>
#include <linux/seccomp.h>
#include <linux/sockios.h>
#include <linux/wait.h>
#include <linux/icmpv6.h>
#include <linux/serial.h>
#include <linux/can.h>
#include <linux/vm_sockets.h>
#include <linux/taskstats.h>
#include <linux/genetlink.h>
#include <linux/watchdog.h>
#include <net/route.h>
#include <asm/termbits.h>

#ifndef MSG_FASTOPEN
#define MSG_FASTOPEN    0x20000000
#endif

#ifndef PTRACE_GETREGS
#define PTRACE_GETREGS	0xc
#endif

#ifndef PTRACE_SETREGS
#define PTRACE_SETREGS	0xd
#endif

#ifndef SOL_NETLINK
#define SOL_NETLINK	270
#endif

#ifdef SOL_BLUETOOTH
// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h
// but it is already in bluetooth_linux.go
#undef SOL_BLUETOOTH
#endif

// Certain constants are missing from the fs/crypto UAPI
#define FS_KEY_DESC_PREFIX              "fscrypt:"
#define FS_KEY_DESC_PREFIX_SIZE         8
#define FS_MAX_KEY_SIZE                 64
'

includes_NetBSD='
#include <sys/types.h>
#include <sys/param.h>
#include <sys/event.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/sysctl.h>
#include <sys/termios.h>
#include <sys/ttycom.h>
#include <sys/wait.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/route.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/ip_mroute.h>
#include <netinet/if_ether.h>

// Needed since <sys/param.h> refers to it...
#define schedppq 1
'

includes_OpenBSD='
#include <sys/types.h>
#include <sys/param.h>
#include <sys/event.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/sysctl.h>
#include <sys/termios.h>
#include <sys/ttycom.h>
#include <sys/wait.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/if_var.h>
#include <net/route.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/ip_mroute.h>
#include <netinet/if_ether.h>
#include <net/if_bridge.h>

// We keep some constants not supported in OpenBSD 5.5 and beyond for
// the promise of compatibility.
#define EMUL_ENABLED		0x1
#define EMUL_NATIVE		0x2
#define IPV6_FAITH		0x1d
#define IPV6_OPTIONS		0x1
#define IPV6_RTHDR_STRICT	0x1
#define IPV6_SOCKOPT_RESERVED1	0x3
#define SIOCGIFGENERIC		0xc020693a
#define SIOCSIFGENERIC		0x80206939
#define WALTSIG			0x4
'

includes_SunOS='
#include <limits.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <sys/mkdev.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <net/if_types.h>
#include <net/route.h>
#include <netinet/in.h>
#include <termios.h>
#include <netinet/ip.h>
#include <netinet/ip_mroute.h>
'

includes='
#include <sys/types.h>
#include <sys/file.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip6.h>
#include <netinet/tcp.h>
#include <errno.h>
#include <sys/signal.h>
#include <signal.h>
#include <sys/resource.h>
#include <time.h>
'
ccflags="$@"

# Write go tool cgo -godefs input.
(
	echo package unix
	echo
	echo '/*'
	indirect="includes_$(uname)"
	echo "${!indirect} $includes"
	echo '*/'
	echo 'import "C"'
	echo 'import "syscall"'
	echo
	echo 'const ('

	# The gcc command line prints all the #defines
	# it encounters while processing the input
	echo "${!indirect} $includes" | $CC -x c - -E -dM $ccflags |
	awk '
		$1 != "#define" || $2 ~ /\(/ || $3 == "" {next}

		$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers
		$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}
		$2 ~ /^(SCM_SRCRT)$/ {next}
		$2 ~ /^(MAP_FAILED)$/ {next}
		$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.

		$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||
		$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}

		$2 !~ /^ETH_/ &&
		$2 !~ /^EPROC_/ &&
		$2 !~ /^EQUIV_/ &&
		$2 !~ /^EXPR_/ &&
		$2 ~ /^E[A-Z0-9_]+$/ ||
		$2 ~ /^B[0-9_]+$/ ||
		$2 ~ /^(OLD|NEW)DEV$/ ||
		$2 == "BOTHER" ||
		$2 ~ /^CI?BAUD(EX)?$/ ||
		$2 == "IBSHIFT" ||
		$2 ~ /^V[A-Z0-9]+$/ ||
		$2 ~ /^CS[A-Z0-9]/ ||
		$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||
		$2 ~ /^IGN/ ||
		$2 ~ /^IX(ON|ANY|OFF)$/ ||
		$2 ~ /^IN(LCR|PCK)$/ ||
		$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||
		$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||
		$2 == "BRKINT" ||
		$2 == "HUPCL" ||
		$2 == "PENDIN" ||
		$2 == "TOSTOP" ||
		$2 == "XCASE" ||
		$2 == "ALTWERASE" ||
		$2 == "NOKERNINFO" ||
		$2 ~ /^PAR/ ||
		$2 ~ /^SIG[^_]/ ||
		$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||
		$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||
		$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||
		$2 ~ /^O?XTABS$/ ||
		$2 ~ /^TC[IO](ON|OFF)$/ ||
		$2 ~ /^IN_/ ||
		$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||
		$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ ||
		$2 ~ /^FALLOC_/ ||
		$2 == "ICMPV6_FILTER" ||
		$2 == "SOMAXCONN" ||
		$2 == "NAME_MAX" ||
		$2 == "IFNAMSIZ" ||
		$2 ~ /^CTL_(MAXNAME|NET|QUERY)$/ ||
		$2 ~ /^SYSCTL_VERS/ ||
		$2 ~ /^(MS|MNT|UMOUNT)_/ ||
		$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||
		$2 ~ /^(O|F|E?FD|NAME|S|PTRACE|PT)_/ ||
		$2 ~ /^LINUX_REBOOT_CMD_/ ||
		$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||
		$2 !~ "NLA_TYPE_MASK" &&
		$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P)_/ ||
		$2 ~ /^SIOC/ ||
		$2 ~ /^TIOC/ ||
		$2 ~ /^TCGET/ ||
		$2 ~ /^TCSET/ ||
		$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||
		$2 !~ "RTF_BITS" &&
		$2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ ||
		$2 ~ /^BIOC/ ||
		$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||
		$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ ||
		$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||
		$2 ~ /^CLONE_[A-Z_]+/ ||
		$2 !~ /^(BPF_TIMEVAL)$/ &&
		$2 ~ /^(BPF|DLT)_/ ||
		$2 ~ /^CLOCK_/ ||
		$2 ~ /^CAN_/ ||
		$2 ~ /^CAP_/ ||
		$2 ~ /^ALG_/ ||
		$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE|IOC_(GET|SET)_ENCRYPTION)/ ||
		$2 ~ /^GRND_/ ||
		$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||
		$2 ~ /^KEYCTL_/ ||
		$2 ~ /^PERF_EVENT_IOC_/ ||
		$2 ~ /^SECCOMP_MODE_/ ||
		$2 ~ /^SPLICE_/ ||
		$2 ~ /^(VM|VMADDR)_/ ||
		$2 ~ /^(TASKSTATS|TS)_/ ||
		$2 ~ /^GENL_/ ||
		$2 ~ /^UTIME_/ ||
		$2 ~ /^XATTR_(CREATE|REPLACE)/ ||
		$2 ~ /^WDIOC_/ ||
		$2 !~ "WMESGLEN" &&
		$2 ~ /^W[A-Z0-9]+$/ ||
		$2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf("\t%s = C.%s\n", $2, $2)}
		$2 ~ /^__WCOREFLAG$/ {next}
		$2 ~ /^__W[A-Z0-9]+$/ {printf("\t%s = C.%s\n", substr($2,3), $2)}

		{next}
	' | sort

	echo ')'
) >_const.go

# Pull out the error names for later.
errors=$(
	echo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |
	awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |
	sort
)

# Pull out the signal names for later.
signals=$(
	echo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |
	awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |
	egrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' |
	sort
)

# Again, writing regexps to a file.
echo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |
	awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print "^\t" $2 "[ \t]*=" }' |
	sort >_error.grep
echo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |
	awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print "^\t" $2 "[ \t]*=" }' |
	egrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' |
	sort >_signal.grep

echo '// mkerrors.sh' "$@"
echo '// Code generated by the command above; see README.md. DO NOT EDIT.'
echo
echo "// +build ${GOARCH},${GOOS}"
echo
go tool cgo -godefs -- "$@" _const.go >_error.out
cat _error.out | grep -vf _error.grep | grep -vf _signal.grep
echo
echo '// Errors'
echo 'const ('
cat _error.out | grep -f _error.grep | sed 's/=\(.*\)/= syscall.Errno(\1)/'
echo ')'

echo
echo '// Signals'
echo 'const ('
cat _error.out | grep -f _signal.grep | sed 's/=\(.*\)/= syscall.Signal(\1)/'
echo ')'

# Run C program to print error and syscall strings.
(
	echo -E "
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <ctype.h>
#include <string.h>
#include <signal.h>

#define nelem(x) (sizeof(x)/sizeof((x)[0]))

enum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below

int errors[] = {
"
	for i in $errors
	do
		echo -E '	'$i,
	done

	echo -E "
};

int signals[] = {
"
	for i in $signals
	do
		echo -E '	'$i,
	done

	# Use -E because on some systems bash builtin interprets \n itself.
	echo -E '
};

static int
intcmp(const void *a, const void *b)
{
	return *(int*)a - *(int*)b;
}

int
main(void)
{
	int i, e;
	char buf[1024], *p;

	printf("\n\n// Error table\n");
	printf("var errors = [...]string {\n");
	qsort(errors, nelem(errors), sizeof errors[0], intcmp);
	for(i=0; i<nelem(errors); i++) {
		e = errors[i];
		if(i > 0 && errors[i-1] == e)
			continue;
		strcpy(buf, strerror(e));
		// lowercase first letter: Bad -> bad, but STREAM -> STREAM.
		if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)
			buf[0] += a - A;
		printf("\t%d: \"%s\",\n", e, buf);
	}
	printf("}\n\n");

	printf("\n\n// Signal table\n");
	printf("var signals = [...]string {\n");
	qsort(signals, nelem(signals), sizeof signals[0], intcmp);
	for(i=0; i<nelem(signals); i++) {
		e = signals[i];
		if(i > 0 && signals[i-1] == e)
			continue;
		strcpy(buf, strsignal(e));
		// lowercase first letter: Bad -> bad, but STREAM -> STREAM.
		if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)
			buf[0] += a - A;
		// cut trailing : number.
		p = strrchr(buf, ":"[0]);
		if(p)
			*p = '\0';
		printf("\t%d: \"%s\",\n", e, buf);
	}
	printf("}\n\n");

	return 0;
}

'
) >_errors.c

$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out


#!/bin/bash

set -e

echo "Updating ${GOPATH}"

to_fix=$(ls "${GOPATH}/src/k8s.io/kubernetes/staging/src/k8s.io")
for item in $to_fix; do
   echo "Updating staging dep ${item}"
   rm -rf "${GOPATH}/src/k8s.io/${item}"
   mkdir "${GOPATH}/src/k8s.io/${item}"
   cd "${GOPATH}/src/k8s.io/${item}"
   git init
   # shellcheck disable=SC2086
   cp -R ${GOPATH}/src/k8s.io/kubernetes/staging/src/k8s.io/${item}/* ./
   git add .
   git commit -a -m from_staging
done

with_vendor=$(find "${GOPATH}/src/" -type d | grep vendor | grep -v 'vendor/')
for item in $with_vendor; do
    echo "Removing vendor from ${item}"
    (cd "$item")
    rm -rf "$item"
    git commit -a -m no_vendor
done

echo Overriding AKS API
mkdir -p "${GOPATH}/src/github.com/Azure/azure-sdk-for-go/services/containerservice/mgmt/2018-03-31/containerservice"
# shellcheck disable=SC2086
cp ${GOPATH}/src/k8s.io/autoscaler/cluster-autoscaler/_override/github.com/Azure/azure-sdk-for-go/services/containerservice/mgmt/2018-03-31/containerservice/* "${GOPATH}/src/github.com/Azure/azure-sdk-for-go/services/containerservice/mgmt/2018-03-31/containerservice/"
cd "${GOPATH}/src/github.com/Azure/azure-sdk-for-go/services/containerservice/mgmt/2018-03-31/containerservice"
git add .
git commit -a -m "Api override for AKS"

echo Overriding Azure autorest
# shellcheck disable=SC2086
cp -r ${GOPATH}/src/k8s.io/autoscaler/cluster-autoscaler/_override/github.com/Azure/go-autorest/* "${GOPATH}/src/github.com/Azure/go-autorest/"
cd "${GOPATH}/src/github.com/Azure/go-autorest/"
git add .
git commit -a -m "Api override for autorest"


#!/bin/bash

# Copyright 2017 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

IMAGE_TO_PUSH=$1
if [ -z $IMAGE_TO_PUSH ]; then
  echo No image passed
  exit 1
fi

docker_push_cmd=("docker")
if [[ "${IMAGE_TO_PUSH}" == "gcr.io/"* ]] || [[ "${IMAGE_TO_PUSH}" == "staging-k8s.gcr.io/"* ]] ; then
    docker_push_cmd=("gcloud" "docker" "--")
fi

echo "About to push image $IMAGE_TO_PUSH"
read -r -p "Are you sure? [y/N] " response
if [[ "$response" =~ ^([yY])+$ ]]; then
  "${docker_push_cmd[@]}" pull $IMAGE_TO_PUSH
  if [ $? -eq 0 ]; then
    echo $IMAGE_TO_PUSH already exists
    exit 1
  fi
  "${docker_push_cmd[@]}" push $IMAGE_TO_PUSH
else
  echo Aborted
  exit 1
fi


#!/bin/bash -e
#
# This script rebuilds the generated code for the protocol buffers.
# To run this you will need protoc and goprotobuf installed;
# see https://github.com/golang/protobuf for instructions.

PKG=google.golang.org/appengine

function die() {
	echo 1>&2 $*
	exit 1
}

# Sanity check that the right tools are accessible.
for tool in go protoc protoc-gen-go; do
	q=$(which $tool) || die "didn't find $tool"
	echo 1>&2 "$tool: $q"
done

echo -n 1>&2 "finding package dir... "
pkgdir=$(go list -f '{{.Dir}}' $PKG)
echo 1>&2 $pkgdir
base=$(echo $pkgdir | sed "s,/$PKG\$,,")
echo 1>&2 "base: $base"
cd $base

# Run protoc once per package.
for dir in $(find $PKG/internal -name '*.proto' | xargs dirname | sort | uniq); do
	echo 1>&2 "* $dir"
	protoc --go_out=. $dir/*.proto
done

for f in $(find $PKG/internal -name '*.pb.go'); do
  # Remove proto.RegisterEnum calls.
  # These cause duplicate registration panics when these packages
  # are used on classic App Engine. proto.RegisterEnum only affects
  # parsing the text format; we don't care about that.
  # https://code.google.com/p/googleappengine/issues/detail?id=11670#c17
  sed -i '/proto.RegisterEnum/d' $f
done


#env /usr/bin/bash

set -o errexit
set -o pipefail
set -o nounset
shopt -s lastpipe

if [[ $(basename $(pwd)) != "cluster-autoscaler" ]];then
  echo "The script must be run in cluster-autoscaler directory"
  exit 1
fi

if ! which jq > /dev/null; then
  echo "This script requires jq command to be available"
  exit 1
fi

SCRIPT_NAME=$(basename "$0")
K8S_FORK="git@github.com:kubernetes/kubernetes.git"
K8S_REV="master"
BATCH_MODE="false"
TARGET_MODULE=${TARGET_MODULE:-k8s.io/autoscaler/cluster-autoscaler}

ARGS="$@"
OPTS=`getopt -o f::r::d::v::b:: --long k8sfork::,k8srev::,workdir::,batch:: -n $SCRIPT_NAME -- "$@"`
if [ $? != 0 ] ; then echo "Failed parsing options." >&2 ; exit 1 ; fi
eval set -- "$OPTS"
while true; do
  case "$1" in
    -f | --k8sfork ) K8S_FORK="$2"; shift; shift ;;
    -r | --k8srev ) K8S_REV="$2"; shift; shift ;;
    -d | --workdir ) WORK_DIR="$2"; shift; shift ;;
    -b | --batch ) BATCH_MODE="true"; shift; shift ;;
    -v ) VERBOSE=1; shift; if [[ "$1" == "v" ]]; then VERBOSE=2; shift; fi; ;;
    -- ) shift; break ;;
    * ) break ;;
  esac
done

export GO111MODULE=on

set -o errexit
WORK_DIR="${WORK_DIR:-$(mktemp -d /tmp/ca-update-vendor.XXXX)}"
echo "Operating in ${WORK_DIR}"

if [ ! -d $WORK_DIR ]; then
  echo "Work dir ${WORK_DIR} does not exist"
  exit 1
fi

LOG_FILE="${LOG_FILE:-${WORK_DIR}/ca-update-vendor.log}"
echo "Sending logs to: ${LOG_FILE}"
if [ -z "${BASH_XTRACEFD:-}" ]; then
  exec 19> "${LOG_FILE}"
  export BASH_XTRACEFD="19"
fi
set -x

EXPECTED_ERROR_MARKER="${WORK_DIR}/expected_error"

# Try
set +o errexit
(
  set -o errexit
  rm -f $EXPECTED_ERROR_MARKER
  K8S_REPO="${WORK_DIR}/kubernetes"
  if [ -d ${K8S_REPO} ]; then
    pushd ${K8S_REPO} >/dev/null
    if [[ "$(git remote get-url origin)" != "${K8S_FORK}" ]]; then
      echo "Mismated checked out k8s repo; deleting"
      rm -rf "${K8S_REPO}"
    fi
    popd >/dev/null
  fi

  echo "Updating vendor against ${K8S_FORK}:${K8S_REV}"

  if [ ! -d ${K8S_REPO} ]; then
    echo "Cloning ${K8S_FORK} into ${K8S_REPO}"
    git clone ${K8S_FORK} ${K8S_REPO} >&${BASH_XTRACEFD} 2>&1
  fi

  pushd ${K8S_REPO} >/dev/null
  git checkout ${K8S_REV} >&${BASH_XTRACEFD} 2>&1
  K8S_REV_PARSED=$(git rev-parse ${K8S_REV})
  popd >/dev/null

  function err_rerun() {
    touch ${EXPECTED_ERROR_MARKER}
    echo "$*"
    if [[ "${BATCH_MODE}" == "false" ]]; then
      echo "Fix errors and rerun script:"
      echo " $0 -d${WORK_DIR} -f${K8S_FORK} -r${K8S_REV}"
    fi
    exit 1
  }

  # Deleting old stuff
  rm -rf vendor
  rm -f go.mod
  rm -f go.sum

  # Base CA go.mod on one from k8s.io/kuberntes
  cp $K8S_REPO/go.mod .

  # Check go version
  REQUIRED_GO_VERSION=$(cat go.mod  |grep '^go ' |tr -s ' ' |cut -d ' '  -f 2)
  USED_GO_VERSION=$(go version |sed 's/.*go\([0-9]\+\.[0-9]\+\).*/\1/')

  if [[ "${REQUIRED_GO_VERSION}" != "${USED_GO_VERSION}" ]];then
    err_rerun "Invalid go version ${USED_GO_VERSION}; required go version is ${REQUIRED_GO_VERSION}."
  fi

  # Fix module name and staging modules links
  sed -i "s#module k8s.io/kubernetes#module ${TARGET_MODULE}#" go.mod
  sed -i "s#\\./staging#${K8S_REPO}/staging#" go.mod

  function list_dependencies() {
    local_tmp_dir=$(mktemp -d "${WORK_DIR}/list_dependencies.XXXX")
    local go_dep_file="$1"
    local tmp_file="${local_tmp_dir}/list_dependencies.tmp"
    rm -f ${tmp_file}
    go mod edit -json ${go_dep_file} |jq -r '.Replace[]? | select(.New.Version != null)| "\(.Old.Path) \(.New.Version)"' >> ${tmp_file}
    go mod edit -json ${go_dep_file} |jq -r '.Require[]? | "\(.Path) \(.Version)"' >> ${tmp_file}
    cat ${tmp_file} |sort |uniq
  }

  function version_gt() {
    test "$(printf '%s\n' "$@" | sort -V | head -n 1)" != "$1";
  }

  OLD_EXTRA_FOUND="false"
  for go_mod_extra in go.mod-extra*; do
    list_dependencies ${go_mod_extra} | while read extra_path extra_version; do
      list_dependencies go.mod | while read source_path source_version; do
        if [[ "${source_path}" == "${extra_path}" ]]; then
          if ! version_gt $extra_version $source_version; then
            echo "Extra dependency ${source_path} already used by k8s in >= version ${source_version}"
            OLD_EXTRA_FOUND="true"
          fi
        fi
      done
    done
  done
  if [[ "${OLD_EXTRA_FOUND}" == "true" ]]; then
    err_rerun "Extra dependencies found in one of go.mod-extra files"
  fi

  # Add dependencies from go.mod-extra to go.mod
  # Propagate require entries to both require and replace
  for go_mod_extra in go.mod-extra*; do
    go mod edit -json ${go_mod_extra} | jq -r '.Require[]? | "-require \(.Path)@\(.Version)"' | xargs -t -r go mod edit >&${BASH_XTRACEFD} 2>&1
    go mod edit -json ${go_mod_extra} | jq -r '.Require[]? | "-replace \(.Path)=\(.Path)@\(.Version)"' | xargs -t -r go mod edit >&${BASH_XTRACEFD} 2>&1
    # And add explicit replace entries
    go mod edit -json ${go_mod_extra} | jq -r '.Replace[]? | "-replace \(.Old.Path)=\(.New.Path)@\(.New.Version)"' | sed "s/@null//g" |xargs -t -r go mod edit >&${BASH_XTRACEFD} 2>&1
  done
  # Add k8s.io/kubernetes dependency
  go mod edit -require k8s.io/kubernetes@v0.0.0
  go mod edit -replace k8s.io/kubernetes=${K8S_REPO}

  # Fail if there are implicit dependencies
  list_dependencies go.mod > ${WORK_DIR}/packages-before-tidy
  go mod tidy -v >&${BASH_XTRACEFD} 2>&1
  list_dependencies go.mod > ${WORK_DIR}/packages-after-tidy

  IMPLICIT_FOUND="false"
  set +o pipefail
  diff -u ${WORK_DIR}/packages-before-tidy ${WORK_DIR}/packages-after-tidy | grep -v '\+\+\+ ' | grep '^\+' | cut -b 2- |while read line; do
    IMPLICIT_FOUND="true"
    echo "Implicit dependency found: ${line}"
  done
  set -o pipefail

  if [[ "${IMPLICIT_FOUND}" == "true" ]]; then
    err_rerun "Implicit dependencies missing from go.mod-extra"
  fi

  echo "Running go mod vendor"
  go mod vendor

  echo "Running go test -mod=vendor ./..."
  if ! go test -mod=vendor ./... >&${BASH_XTRACEFD} 2>&1; then
    err_rerun "Test run failed"
  fi

  # Commit go.mod* and vendor
  git restore --staged . >&${BASH_XTRACEFD} 2>&1
  git add vendor go.mod go.sum >&${BASH_XTRACEFD} 2>&1
  if ! git diff --quiet --cached; then
    echo "Commiting vendor, go.mod and go.sum"
    git ci -m "Updating vendor against ${K8S_FORK}:${K8S_REV} (${K8S_REV_PARSED})" >&${BASH_XTRACEFD} 2>&1
  else
    echo "No changes after vendor update; skipping commit"
  fi

  if ! git diff --quiet; then
    echo "Uncommited changes (manual fixes?) still present in repository - please commit those"
  fi

  echo "Operation finished successfully"
  if [[ "$(basename "${WORK_DIR}" | cut -d '.' -f 1)" == "ca-update-vendor" ]];then
    echo "Deleting working directory ${WORK_DIR}"
    rm -rf ${WORK_DIR}
  else
    echo "Preserving working directory ${WORK_DIR}"
  fi
)

# Catch
err=$?
if [[ $err -ne 0 ]]; then
  if [ ! -f "${EXPECTED_ERROR_MARKER}" ]; then
    echo
    echo "Unexpected error occured; check $LOG_FILE"
  fi
fi
exit $err


#go test -run=none -file bench_test.go -test.bench . -cpuprofile=bench_test.out

go test -c
./go-restful.test -test.run=none -test.cpuprofile=tmp.prof -test.bench=BenchmarkMany
./go-restful.test -test.run=none -test.cpuprofile=curly.prof -test.bench=BenchmarkManyCurly

#go tool pprof go-restful.test tmp.prof
go tool pprof go-restful.test curly.prof


go test -coverprofile=coverage.out
go tool cover -html=coverage.out


#!/usr/bin/env bash

set -e
echo "" > coverage.txt

for d in $(go list ./... | grep -v vendor); do
    echo -e "TESTS FOR: for \033[0;35m${d}\033[0m"
    go test -race -v -coverprofile=profile.coverage.out -covermode=atomic $d
    if [ -f profile.coverage.out ]; then
        cat profile.coverage.out >> coverage.txt
        rm profile.coverage.out
    fi
    echo ""
done


#!/usr/bin/env bash

set -e
echo "" > coverage.txt

for d in $(go list github.com/modern-go/reflect2-tests/... | grep -v vendor); do
    go test -coverprofile=profile.out -coverpkg=github.com/modern-go/reflect2 $d
    if [ -f profile.out ]; then
        cat profile.out >> coverage.txt
        rm profile.out
    fi
done


#!/usr/bin/env bash
# Copyright 2009 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.

# This script runs or (given -n) prints suggested commands to generate files for
# the Architecture/OS specified by the GOARCH and GOOS environment variables.
# See README.md for more information about how the build system works.

GOOSARCH="${GOOS}_${GOARCH}"

# defaults
mksyscall="go run mksyscall.go"
mkerrors="./mkerrors.sh"
zerrors="zerrors_$GOOSARCH.go"
mksysctl=""
zsysctl="zsysctl_$GOOSARCH.go"
mksysnum=
mktypes=
mkasm=
run="sh"
cmd=""

case "$1" in
-syscalls)
	for i in zsyscall*go
	do
		# Run the command line that appears in the first line
		# of the generated file to regenerate it.
		sed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i
		rm _$i
	done
	exit 0
	;;
-n)
	run="cat"
	cmd="echo"
	shift
esac

case "$#" in
0)
	;;
*)
	echo 'usage: mkall.sh [-n]' 1>&2
	exit 2
esac

if [[ "$GOOS" = "linux" ]]; then
	# Use the Docker-based build system
	# Files generated through docker (use $cmd so you can Ctl-C the build or run)
	$cmd docker build --tag generate:$GOOS $GOOS
	$cmd docker run --interactive --tty --volume $(dirname "$(readlink -f "$0")"):/build generate:$GOOS
	exit
fi

GOOSARCH_in=syscall_$GOOSARCH.go
case "$GOOSARCH" in
_* | *_ | _)
	echo 'undefined $GOOS_$GOARCH:' "$GOOSARCH" 1>&2
	exit 1
	;;
aix_ppc)
	mkerrors="$mkerrors -maix32"
	mksyscall="go run mksyscall_aix_ppc.go -aix"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
aix_ppc64)
	mkerrors="$mkerrors -maix64"
	mksyscall="go run mksyscall_aix_ppc64.go -aix"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
darwin_386)
	mkerrors="$mkerrors -m32"
	mksyscall="go run mksyscall.go -l32"
	mksysnum="go run mksysnum.go $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	mkasm="go run mkasm_darwin.go"
	;;
darwin_amd64)
	mkerrors="$mkerrors -m64"
	mksysnum="go run mksysnum.go $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	mkasm="go run mkasm_darwin.go"
	;;
darwin_arm)
	mkerrors="$mkerrors"
	mksyscall="go run mksyscall.go -l32"
	mksysnum="go run mksysnum.go $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	mkasm="go run mkasm_darwin.go"
	;;
darwin_arm64)
	mkerrors="$mkerrors -m64"
	mksysnum="go run mksysnum.go $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	mkasm="go run mkasm_darwin.go"
	;;
dragonfly_amd64)
	mkerrors="$mkerrors -m64"
	mksyscall="go run mksyscall.go -dragonfly"
	mksysnum="go run mksysnum.go 'https://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master'"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
freebsd_386)
	mkerrors="$mkerrors -m32"
	mksyscall="go run mksyscall.go -l32"
	mksysnum="go run mksysnum.go 'https://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master'"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
freebsd_amd64)
	mkerrors="$mkerrors -m64"
	mksysnum="go run mksysnum.go 'https://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master'"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
freebsd_arm)
	mkerrors="$mkerrors"
	mksyscall="go run mksyscall.go -l32 -arm"
	mksysnum="go run mksysnum.go 'https://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master'"
	# Let the type of C char be signed for making the bare syscall
	# API consistent across platforms.
	mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
	;;
freebsd_arm64)
	mkerrors="$mkerrors -m64"
	mksysnum="go run mksysnum.go 'https://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master'"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
netbsd_386)
	mkerrors="$mkerrors -m32"
	mksyscall="go run mksyscall.go -l32 -netbsd"
	mksysnum="go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
netbsd_amd64)
	mkerrors="$mkerrors -m64"
	mksyscall="go run mksyscall.go -netbsd"
	mksysnum="go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
netbsd_arm)
	mkerrors="$mkerrors"
	mksyscall="go run mksyscall.go -l32 -netbsd -arm"
	mksysnum="go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'"
	# Let the type of C char be signed for making the bare syscall
	# API consistent across platforms.
	mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
	;;
openbsd_386)
	mkerrors="$mkerrors -m32"
	mksyscall="go run mksyscall.go -l32 -openbsd"
	mksysctl="./mksysctl_openbsd.pl"
	mksysnum="go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
openbsd_amd64)
	mkerrors="$mkerrors -m64"
	mksyscall="go run mksyscall.go -openbsd"
	mksysctl="./mksysctl_openbsd.pl"
	mksysnum="go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
openbsd_arm)
	mkerrors="$mkerrors"
	mksyscall="go run mksyscall.go -l32 -openbsd -arm"
	mksysctl="./mksysctl_openbsd.pl"
	mksysnum="go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'"
	# Let the type of C char be signed for making the bare syscall
	# API consistent across platforms.
	mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
	;;
solaris_amd64)
	mksyscall="./mksyscall_solaris.pl"
	mkerrors="$mkerrors -m64"
	mksysnum=
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
*)
	echo 'unrecognized $GOOS_$GOARCH: ' "$GOOSARCH" 1>&2
	exit 1
	;;
esac

(
	if [ -n "$mkerrors" ]; then echo "$mkerrors |gofmt >$zerrors"; fi
	case "$GOOS" in
	*)
		syscall_goos="syscall_$GOOS.go"
		case "$GOOS" in
		darwin | dragonfly | freebsd | netbsd | openbsd)
			syscall_goos="syscall_bsd.go $syscall_goos"
			;;
		esac
		if [ -n "$mksyscall" ]; then
			if [ "$GOOSARCH" == "aix_ppc64" ]; then
				# aix/ppc64 script generates files instead of writing to stdin.
				echo "$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_"$GOOSARCH"_gccgo.go && gofmt -w zsyscall_"$GOOSARCH"_gc.go " ;
			elif [ "$GOOS" == "darwin" ]; then
			        # pre-1.12, direct syscalls
			        echo "$mksyscall -tags $GOOS,$GOARCH,!go1.12 $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.1_11.go";
			        # 1.12 and later, syscalls via libSystem
				echo "$mksyscall -tags $GOOS,$GOARCH,go1.12 $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go";
			else
				echo "$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go";
			fi
		fi
	esac
	if [ -n "$mksysctl" ]; then echo "$mksysctl |gofmt >$zsysctl"; fi
	if [ -n "$mksysnum" ]; then echo "$mksysnum |gofmt >zsysnum_$GOOSARCH.go"; fi
	if [ -n "$mktypes" ]; then
		echo "$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go";
	if [ -n "$mkasm" ]; then echo "$mkasm $GOARCH"; fi
	fi
) | $run


#!/usr/bin/env bash
# Copyright 2009 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.

# Generate Go code listing errors and other #defined constant
# values (ENAMETOOLONG etc.), by asking the preprocessor
# about the definitions.

unset LANG
export LC_ALL=C
export LC_CTYPE=C

if test -z "$GOARCH" -o -z "$GOOS"; then
	echo 1>&2 "GOARCH or GOOS not defined in environment"
	exit 1
fi

# Check that we are using the new build system if we should
if [[ "$GOOS" = "linux" ]] && [[ "$GOLANG_SYS_BUILD" != "docker" ]]; then
	echo 1>&2 "In the Docker based build system, mkerrors should not be called directly."
	echo 1>&2 "See README.md"
	exit 1
fi

if [[ "$GOOS" = "aix" ]]; then
	CC=${CC:-gcc}
else
	CC=${CC:-cc}
fi

if [[ "$GOOS" = "solaris" ]]; then
	# Assumes GNU versions of utilities in PATH.
	export PATH=/usr/gnu/bin:$PATH
fi

uname=$(uname)

includes_AIX='
#include <net/if.h>
#include <net/netopt.h>
#include <netinet/ip_mroute.h>
#include <sys/protosw.h>
#include <sys/stropts.h>
#include <sys/mman.h>
#include <sys/poll.h>
#include <sys/termio.h>
#include <termios.h>
#include <fcntl.h>

#define AF_LOCAL AF_UNIX
'

includes_Darwin='
#define _DARWIN_C_SOURCE
#define KERNEL
#define _DARWIN_USE_64_BIT_INODE
#include <stdint.h>
#include <sys/attr.h>
#include <sys/types.h>
#include <sys/event.h>
#include <sys/ptrace.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/sysctl.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/utsname.h>
#include <sys/wait.h>
#include <sys/xattr.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/route.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <termios.h>
'

includes_DragonFly='
#include <sys/types.h>
#include <sys/event.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/route.h>
#include <netinet/in.h>
#include <termios.h>
#include <netinet/ip.h>
#include <net/ip_mroute/ip_mroute.h>
'

includes_FreeBSD='
#include <sys/capsicum.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/event.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/route.h>
#include <netinet/in.h>
#include <termios.h>
#include <netinet/ip.h>
#include <netinet/ip_mroute.h>
#include <sys/extattr.h>

#if __FreeBSD__ >= 10
#define IFT_CARP	0xf8	// IFT_CARP is deprecated in FreeBSD 10
#undef SIOCAIFADDR
#define SIOCAIFADDR	_IOW(105, 26, struct oifaliasreq)	// ifaliasreq contains if_data
#undef SIOCSIFPHYADDR
#define SIOCSIFPHYADDR	_IOW(105, 70, struct oifaliasreq)	// ifaliasreq contains if_data
#endif
'

includes_Linux='
#define _LARGEFILE_SOURCE
#define _LARGEFILE64_SOURCE
#ifndef __LP64__
#define _FILE_OFFSET_BITS 64
#endif
#define _GNU_SOURCE

// <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of
// these structures. We just include them copied from <bits/termios.h>.
#if defined(__powerpc__)
struct sgttyb {
        char    sg_ispeed;
        char    sg_ospeed;
        char    sg_erase;
        char    sg_kill;
        short   sg_flags;
};

struct tchars {
        char    t_intrc;
        char    t_quitc;
        char    t_startc;
        char    t_stopc;
        char    t_eofc;
        char    t_brkc;
};

struct ltchars {
        char    t_suspc;
        char    t_dsuspc;
        char    t_rprntc;
        char    t_flushc;
        char    t_werasc;
        char    t_lnextc;
};
#endif

#include <bits/sockaddr.h>
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <sys/inotify.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/signalfd.h>
#include <sys/socket.h>
#include <sys/xattr.h>
#include <linux/errqueue.h>
#include <linux/if.h>
#include <linux/if_alg.h>
#include <linux/if_arp.h>
#include <linux/if_ether.h>
#include <linux/if_ppp.h>
#include <linux/if_tun.h>
#include <linux/if_packet.h>
#include <linux/if_addr.h>
#include <linux/falloc.h>
#include <linux/filter.h>
#include <linux/fs.h>
#include <linux/kexec.h>
#include <linux/keyctl.h>
#include <linux/magic.h>
#include <linux/memfd.h>
#include <linux/module.h>
#include <linux/netfilter/nfnetlink.h>
#include <linux/netlink.h>
#include <linux/net_namespace.h>
#include <linux/perf_event.h>
#include <linux/random.h>
#include <linux/reboot.h>
#include <linux/rtnetlink.h>
#include <linux/ptrace.h>
#include <linux/sched.h>
#include <linux/seccomp.h>
#include <linux/sockios.h>
#include <linux/wait.h>
#include <linux/icmpv6.h>
#include <linux/serial.h>
#include <linux/can.h>
#include <linux/vm_sockets.h>
#include <linux/taskstats.h>
#include <linux/genetlink.h>
#include <linux/watchdog.h>
#include <linux/hdreg.h>
#include <linux/rtc.h>
#include <linux/if_xdp.h>
#include <mtd/ubi-user.h>
#include <net/route.h>

#if defined(__sparc__)
// On sparc{,64}, the kernel defines struct termios2 itself which clashes with the
// definition in glibc. As only the error constants are needed here, include the
// generic termibits.h (which is included by termbits.h on sparc).
#include <asm-generic/termbits.h>
#else
#include <asm/termbits.h>
#endif

#ifndef MSG_FASTOPEN
#define MSG_FASTOPEN    0x20000000
#endif

#ifndef PTRACE_GETREGS
#define PTRACE_GETREGS	0xc
#endif

#ifndef PTRACE_SETREGS
#define PTRACE_SETREGS	0xd
#endif

#ifndef SOL_NETLINK
#define SOL_NETLINK	270
#endif

#ifdef SOL_BLUETOOTH
// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h
// but it is already in bluetooth_linux.go
#undef SOL_BLUETOOTH
#endif

// Certain constants are missing from the fs/crypto UAPI
#define FS_KEY_DESC_PREFIX              "fscrypt:"
#define FS_KEY_DESC_PREFIX_SIZE         8
#define FS_MAX_KEY_SIZE                 64
'

includes_NetBSD='
#include <sys/types.h>
#include <sys/param.h>
#include <sys/event.h>
#include <sys/extattr.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/sysctl.h>
#include <sys/termios.h>
#include <sys/ttycom.h>
#include <sys/wait.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/route.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/ip_mroute.h>
#include <netinet/if_ether.h>

// Needed since <sys/param.h> refers to it...
#define schedppq 1
'

includes_OpenBSD='
#include <sys/types.h>
#include <sys/param.h>
#include <sys/event.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/termios.h>
#include <sys/ttycom.h>
#include <sys/unistd.h>
#include <sys/wait.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/if_var.h>
#include <net/route.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/ip_mroute.h>
#include <netinet/if_ether.h>
#include <net/if_bridge.h>

// We keep some constants not supported in OpenBSD 5.5 and beyond for
// the promise of compatibility.
#define EMUL_ENABLED		0x1
#define EMUL_NATIVE		0x2
#define IPV6_FAITH		0x1d
#define IPV6_OPTIONS		0x1
#define IPV6_RTHDR_STRICT	0x1
#define IPV6_SOCKOPT_RESERVED1	0x3
#define SIOCGIFGENERIC		0xc020693a
#define SIOCSIFGENERIC		0x80206939
#define WALTSIG			0x4
'

includes_SunOS='
#include <limits.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <sys/mkdev.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <net/if_types.h>
#include <net/route.h>
#include <netinet/in.h>
#include <termios.h>
#include <netinet/ip.h>
#include <netinet/ip_mroute.h>
'

includes='
#include <sys/types.h>
#include <sys/file.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip6.h>
#include <netinet/tcp.h>
#include <errno.h>
#include <sys/signal.h>
#include <signal.h>
#include <sys/resource.h>
#include <time.h>
'
ccflags="$@"

# Write go tool cgo -godefs input.
(
	echo package unix
	echo
	echo '/*'
	indirect="includes_$(uname)"
	echo "${!indirect} $includes"
	echo '*/'
	echo 'import "C"'
	echo 'import "syscall"'
	echo
	echo 'const ('

	# The gcc command line prints all the #defines
	# it encounters while processing the input
	echo "${!indirect} $includes" | $CC -x c - -E -dM $ccflags |
	awk '
		$1 != "#define" || $2 ~ /\(/ || $3 == "" {next}

		$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers
		$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}
		$2 ~ /^(SCM_SRCRT)$/ {next}
		$2 ~ /^(MAP_FAILED)$/ {next}
		$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.

		$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||
		$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}

		$2 !~ /^ECCAPBITS/ &&
		$2 !~ /^ETH_/ &&
		$2 !~ /^EPROC_/ &&
		$2 !~ /^EQUIV_/ &&
		$2 !~ /^EXPR_/ &&
		$2 ~ /^E[A-Z0-9_]+$/ ||
		$2 ~ /^B[0-9_]+$/ ||
		$2 ~ /^(OLD|NEW)DEV$/ ||
		$2 == "BOTHER" ||
		$2 ~ /^CI?BAUD(EX)?$/ ||
		$2 == "IBSHIFT" ||
		$2 ~ /^V[A-Z0-9]+$/ ||
		$2 ~ /^CS[A-Z0-9]/ ||
		$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||
		$2 ~ /^IGN/ ||
		$2 ~ /^IX(ON|ANY|OFF)$/ ||
		$2 ~ /^IN(LCR|PCK)$/ ||
		$2 !~ "X86_CR3_PCID_NOFLUSH" &&
		$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||
		$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||
		$2 == "BRKINT" ||
		$2 == "HUPCL" ||
		$2 == "PENDIN" ||
		$2 == "TOSTOP" ||
		$2 == "XCASE" ||
		$2 == "ALTWERASE" ||
		$2 == "NOKERNINFO" ||
		$2 ~ /^PAR/ ||
		$2 ~ /^SIG[^_]/ ||
		$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||
		$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||
		$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||
		$2 ~ /^O?XTABS$/ ||
		$2 ~ /^TC[IO](ON|OFF)$/ ||
		$2 ~ /^IN_/ ||
		$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||
		$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ ||
		$2 ~ /^TP_STATUS_/ ||
		$2 ~ /^FALLOC_/ ||
		$2 == "ICMPV6_FILTER" ||
		$2 == "SOMAXCONN" ||
		$2 == "NAME_MAX" ||
		$2 == "IFNAMSIZ" ||
		$2 ~ /^CTL_(HW|KERN|MAXNAME|NET|QUERY)$/ ||
		$2 ~ /^KERN_(HOSTNAME|OS(RELEASE|TYPE)|VERSION)$/ ||
		$2 ~ /^HW_MACHINE$/ ||
		$2 ~ /^SYSCTL_VERS/ ||
		$2 !~ "MNT_BITS" &&
		$2 ~ /^(MS|MNT|UMOUNT)_/ ||
		$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||
		$2 ~ /^(O|F|[ES]?FD|NAME|S|PTRACE|PT)_/ ||
		$2 ~ /^KEXEC_/ ||
		$2 ~ /^LINUX_REBOOT_CMD_/ ||
		$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||
		$2 ~ /^MODULE_INIT_/ ||
		$2 !~ "NLA_TYPE_MASK" &&
		$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ ||
		$2 ~ /^SIOC/ ||
		$2 ~ /^TIOC/ ||
		$2 ~ /^TCGET/ ||
		$2 ~ /^TCSET/ ||
		$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||
		$2 !~ "RTF_BITS" &&
		$2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ ||
		$2 ~ /^BIOC/ ||
		$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||
		$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ ||
		$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||
		$2 ~ /^CLONE_[A-Z_]+/ ||
		$2 !~ /^(BPF_TIMEVAL)$/ &&
		$2 ~ /^(BPF|DLT)_/ ||
		$2 ~ /^(CLOCK|TIMER)_/ ||
		$2 ~ /^CAN_/ ||
		$2 ~ /^CAP_/ ||
		$2 ~ /^ALG_/ ||
		$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE|IOC_(GET|SET)_ENCRYPTION)/ ||
		$2 ~ /^GRND_/ ||
		$2 ~ /^RND/ ||
		$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||
		$2 ~ /^KEYCTL_/ ||
		$2 ~ /^PERF_EVENT_IOC_/ ||
		$2 ~ /^SECCOMP_MODE_/ ||
		$2 ~ /^SPLICE_/ ||
		$2 ~ /^SYNC_FILE_RANGE_/ ||
		$2 !~ /^AUDIT_RECORD_MAGIC/ &&
		$2 !~ /IOC_MAGIC/ &&
		$2 ~ /^[A-Z][A-Z0-9_]+_MAGIC2?$/ ||
		$2 ~ /^(VM|VMADDR)_/ ||
		$2 ~ /^IOCTL_VM_SOCKETS_/ ||
		$2 ~ /^(TASKSTATS|TS)_/ ||
		$2 ~ /^CGROUPSTATS_/ ||
		$2 ~ /^GENL_/ ||
		$2 ~ /^STATX_/ ||
		$2 ~ /^RENAME/ ||
		$2 ~ /^UBI_IOC[A-Z]/ ||
		$2 ~ /^UTIME_/ ||
		$2 ~ /^XATTR_(CREATE|REPLACE|NO(DEFAULT|FOLLOW|SECURITY)|SHOWCOMPRESSION)/ ||
		$2 ~ /^ATTR_(BIT_MAP_COUNT|(CMN|VOL|FILE)_)/ ||
		$2 ~ /^FSOPT_/ ||
		$2 ~ /^WDIOC_/ ||
		$2 ~ /^NFN/ ||
		$2 ~ /^XDP_/ ||
		$2 ~ /^(HDIO|WIN|SMART)_/ ||
		$2 !~ "WMESGLEN" &&
		$2 ~ /^W[A-Z0-9]+$/ ||
		$2 ~/^PPPIOC/ ||
		$2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf("\t%s = C.%s\n", $2, $2)}
		$2 ~ /^__WCOREFLAG$/ {next}
		$2 ~ /^__W[A-Z0-9]+$/ {printf("\t%s = C.%s\n", substr($2,3), $2)}

		{next}
	' | sort

	echo ')'
) >_const.go

# Pull out the error names for later.
errors=$(
	echo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |
	awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |
	sort
)

# Pull out the signal names for later.
signals=$(
	echo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |
	awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |
	egrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT|SIGMAX64)' |
	sort
)

# Again, writing regexps to a file.
echo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |
	awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print "^\t" $2 "[ \t]*=" }' |
	sort >_error.grep
echo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |
	awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print "^\t" $2 "[ \t]*=" }' |
	egrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT|SIGMAX64)' |
	sort >_signal.grep

echo '// mkerrors.sh' "$@"
echo '// Code generated by the command above; see README.md. DO NOT EDIT.'
echo
echo "// +build ${GOARCH},${GOOS}"
echo
go tool cgo -godefs -- "$@" _const.go >_error.out
cat _error.out | grep -vf _error.grep | grep -vf _signal.grep
echo
echo '// Errors'
echo 'const ('
cat _error.out | grep -f _error.grep | sed 's/=\(.*\)/= syscall.Errno(\1)/'
echo ')'

echo
echo '// Signals'
echo 'const ('
cat _error.out | grep -f _signal.grep | sed 's/=\(.*\)/= syscall.Signal(\1)/'
echo ')'

# Run C program to print error and syscall strings.
(
	echo -E "
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <ctype.h>
#include <string.h>
#include <signal.h>

#define nelem(x) (sizeof(x)/sizeof((x)[0]))

enum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below

struct tuple {
	int num;
	const char *name;
};

struct tuple errors[] = {
"
	for i in $errors
	do
		echo -E '	{'$i', "'$i'" },'
	done

	echo -E "
};

struct tuple signals[] = {
"
	for i in $signals
	do
		echo -E '	{'$i', "'$i'" },'
	done

	# Use -E because on some systems bash builtin interprets \n itself.
	echo -E '
};

static int
tuplecmp(const void *a, const void *b)
{
	return ((struct tuple *)a)->num - ((struct tuple *)b)->num;
}

int
main(void)
{
	int i, e;
	char buf[1024], *p;

	printf("\n\n// Error table\n");
	printf("var errorList = [...]struct {\n");
	printf("\tnum  syscall.Errno\n");
	printf("\tname string\n");
	printf("\tdesc string\n");
	printf("} {\n");
	qsort(errors, nelem(errors), sizeof errors[0], tuplecmp);
	for(i=0; i<nelem(errors); i++) {
		e = errors[i].num;
		if(i > 0 && errors[i-1].num == e)
			continue;
		strcpy(buf, strerror(e));
		// lowercase first letter: Bad -> bad, but STREAM -> STREAM.
		if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)
			buf[0] += a - A;
		printf("\t{ %d, \"%s\", \"%s\" },\n", e, errors[i].name, buf);
	}
	printf("}\n\n");

	printf("\n\n// Signal table\n");
	printf("var signalList = [...]struct {\n");
	printf("\tnum  syscall.Signal\n");
	printf("\tname string\n");
	printf("\tdesc string\n");
	printf("} {\n");
	qsort(signals, nelem(signals), sizeof signals[0], tuplecmp);
	for(i=0; i<nelem(signals); i++) {
		e = signals[i].num;
		if(i > 0 && signals[i-1].num == e)
			continue;
		strcpy(buf, strsignal(e));
		// lowercase first letter: Bad -> bad, but STREAM -> STREAM.
		if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)
			buf[0] += a - A;
		// cut trailing : number.
		p = strrchr(buf, ":"[0]);
		if(p)
			*p = '\0';
		printf("\t{ %d, \"%s\", \"%s\" },\n", e, signals[i].name, buf);
	}
	printf("}\n\n");

	return 0;
}

'
) >_errors.c

$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out


#!/bin/bash
set -e

if [[ $GO111MODULE == "on" ]]; then
  go get .
else
  go get -u -v $(go list -f '{{join .Imports "\n"}}{{"\n"}}{{join .TestImports "\n"}}' ./... | sort | uniq | grep -v appengine)
fi

if [[ $GOAPP == "true" ]]; then
  mkdir /tmp/sdk
  curl -o /tmp/sdk.zip "https://storage.googleapis.com/appengine-sdks/featured/go_appengine_sdk_linux_amd64-1.9.68.zip"
  unzip -q /tmp/sdk.zip -d /tmp/sdk
  # NOTE: Set the following env vars in the test script:
  # export PATH="$PATH:/tmp/sdk/go_appengine"
  # export APPENGINE_DEV_APPSERVER=/tmp/sdk/go_appengine/dev_appserver.py
fi


#!/bin/bash
set -e

go version
go test -v google.golang.org/appengine/...
go test -v -race google.golang.org/appengine/...
if [[ $GOAPP == "true" ]]; then
  export PATH="$PATH:/tmp/sdk/go_appengine"
  export APPENGINE_DEV_APPSERVER=/tmp/sdk/go_appengine/dev_appserver.py
  goapp version
  goapp test -v google.golang.org/appengine/...
fi


#!/usr/bin/env bash

# This script serves as an example to demonstrate how to generate the gRPC-Go
# interface and the related messages from .proto file.
#
# It assumes the installation of i) Google proto buffer compiler at
# https://github.com/google/protobuf (after v2.6.1) and ii) the Go codegen
# plugin at https://github.com/golang/protobuf (after 2015-02-20). If you have
# not, please install them first.
#
# We recommend running this script at $GOPATH/src.
#
# If this is not what you need, feel free to make your own scripts. Again, this
# script is for demonstration purpose.
#
proto=$1
protoc --go_out=plugins=grpc:. $proto